题目链接
题目内容
给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
示例 1
输入:digits = [1,2,3]
输出:[1,2,4]
解释:输入数组表示数字 123。
示例 2
输入:digits = [4,3,2,1]
输出:[4,3,2,2]
解释:输入数组表示数字 4321。
解题思路
模拟加法运算,易出错点在于最后得到的结果vector的长度可能会比原来的长度多一,这个时候我们只需要在数组的在最前方插入一个1即可。
代码
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int carry = 1;
for(int i = digits.size()-1; i >= 0; --i)
{
digits[i] = digits[i] + carry;
if(digits[i] > 9)
{
digits[i] = digits[i] - 10;
carry = 1;
}
else
carry = 0;
}
if(carry == 1)
digits.insert(digits.begin(),1);
return digits;
}
};