0. 题目
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.
1. c++ 版本
基本思想就是从vector最后一个元素+1, 注意进位。
vector在首位前插入元素较为耗时
vector<int> plusOne(vector<int>& digits) {
vector<int> result(digits.size(), 0);
int num = 1;
for (int i=digits.size()-1; i>=0; i--){
result[i] = (digits[i] + num) % 10;
num = (digits[i] + num) / 10;
}
if (num > 0)
result.insert(result.begin(), num);
return result;
}
优化:参考 https://leetcode.com/problems/plus-one/discuss/24084/Is-it-a-simple-code(C%2B%2B),
其思想是,
- 如果vector最后一个元素+1 <9, 直接返回digits。
- 如果vector最后一个元素+1 >9, 表示有进位,此时改位置数字为0,其他元素+1处理
-如果vector所有元素+1 >9, 表示所有元素都有进位,此时在vector最后加一个元素0。
TODO,没有执行成功!!
2. python 版本
与上面思想本质一致,只不过python是先将+1的list算出来,然后反序
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
result = []
num = 1
for i in range(len(digits)-1, -1, -1):
result.append((digits[i] + num) % 10)
num = (digits[i] + num) / 10
if num > 0:
result.append(num)
result.reverse()
return result
网友评论