66_Plus-One
66_Plus-One
Description
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Solution
Java solution
class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
for (int i=n-1; i>=0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] newNum = new int[n+1];
newNum[0] = 1;
return newNum;
}
}
Runtime: 0 ms
Python solution 1
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
i = len(digits) - 1
while digits[i] == 9 and i>=0:
digits[i] = 0
i -= 1
if i < 0:
return [1] + digits
else:
digits[i] += 1
return digits
Runtime: 44 ms
Python solution 2
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
num = 0
for i in range(len(digits)):
num += digits[i] * pow(10, len(digits)-1-i)
return [int(n) for n in str(num+1)]
Runtime: 40 ms
Python solution 3
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
return [int(n) for n in str(int(''.join(map(str, digits))) + 1)]
Runtime: 40 ms
随机推荐
- jQuery outerHeight() 方法
outerHeight() 方法返回第一个匹配元素的外部高度. 如下面的图像所示,该方法包含 padding 和 border. 提示:如需包含 margin,请使用 outerHeight(true ...
- 在一般处理程序里面读写session
1.引用命名空间 using System.Web.SessionState; 2.继承IRequiresSessionState接口 3.利用httpcontext类读写即可 context.ses ...
- js判断是移动端还是PC端访问网站
window.location.href = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ? "htt ...
- 解决 UnicodeEncodeError: 'ascii' codec can't encode characters in position 问题
在开头加上 import sys reload(sys) sys.setdefaultencoding( "utf-8" ) Python自然调用ascii编码解码程序去处理字符流 ...
- AVA + Spectron + JavaScript 对 JS 编写的客户端进行自动化测试
什么是 AVA (类似于 unittest) AVA 是一种 JavaScript 单元测试框架,是一个简约的测试库.AVA 它的优势是 JavaScript 的异步特性和并发运行测试, 这反过来提高 ...
- java -io字符流FileWrite操作演示
FileWriter字符输出流演示: /* * FiileWriter 字符流的操作 * FileWriter 的构造方法 可传递 File类型 还可以传递String类型 * * 方法 : * wr ...
- python 缺失值处理(Imputation)
一.缺失值的处理方法 由于各种各样的原因,真实世界中的许多数据集都包含缺失数据,这些数据经常被编码成空格.nans或者是其他的占位符.但是这样的数据集并不能被scikit - learn算法兼容,因为 ...
- idea IDE 导入的项目没有显示目录结构
解决方法:1.关闭 idea 2.删除该项目录下的 .idea 文件 3.重新 open 项目
- RecyclerView的通用适配器
本来这一个主题应该早就写了,只是项目多,属于自己的时间不多,所以现在才开动!! 前一段时间写了一篇文章,是关于ListView,GriView万能适配器,没有看过的同学,可以先看看那篇文章,然后在来学 ...
- ORACLE Sequence 自增长
Sequence是数据库系统按照一定规则自动增加的数字序列.这个序列一般作为代理主键(因为不会重复),没有其他任何意义. Sequence是数据库系统的特性,有的数据库有Sequence,有的没有.比 ...