问题描述:
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
问题分析:
本题目想将一个存在数组中的非负整数加1求和,得到新的整数,我们可以采取倒序遍历,依次求和的方法求解。
下面是我的详细代码:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int flag = 1;
vector<int> res;
for(int i = digits.size() - 1; i >= 0; i--)
{
int sum = flag + digits[i];
res.insert(res.begin(),sum % 10);
flag = sum / 10;
}
if(flag) res.insert(res.begin(),flag);
return res;
}
};