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.
Solutions:
Python
(1)
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits = list(map(str,digits))
digit = list(str(int(''.join(digits))+1))
digits = list(map(int,digit))
return digits
(2)
#方法2和下面的C++思想相同,注意本次的注解部分的小技巧
class Solution:
def plusOne(self, digits):
for i in range(len(digits)):
if digits[~i] < 9: #这里的~波浪号表示倒序输出
digits[~i] += 1
return digits
digits[~i] = 0
return [1] + [0] * len(digits)
列表在遍历的时候i前面加上波浪号则为倒序输出,在网上还没有查到相关解释,下面写个测试代码,解释一下这个小技巧。
Python
=============================
A = [3,4,5,6,7,8]
for i in range(len(A)):
print(~i)
------------------------------
[output]:-1,-2,-3,-4,-5,-6
=============================
A = [3,4,5,6,7,8]
for i in range(len(A)):
print(-i)
------------------------------
[output]:0,-1,-2,-3,-4,-5
=============================
A = [3,4,5,6,7,8]
for i in range(len(A)):
print(i)
------------------------------
[output]:0,1,2,3,4,5
=============================
for i in range(len(A)):
print(A[~i])
------------------------------
[output]:8,7,6,5,4,3
C++
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for(int i = digits.size()-1;i>=0;i--){
if (digits[i] != 9){ #如果digits[i]不为9,直接加一,然后退出
digits[i]++;
break;
}
digits[i] = 0; #如果digits[i]为9的时候,将digits[i]置为0
}
if (digits[0] == 0){ #digits[0] = 0表明了各个位置都是9,则需要在digits前面在加入一个一
digits.insert(digits.begin(),1);
}
return digits;
}
};