题目链接:https://leetcode.com/problems/plus-one/
Given a non-negative number represented as an array of digits, plus one to the number.
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;
for(auto it = digits.rbegin(); it != digits.rend(); it++)
{
int sum = *it + flag;
flag = sum/10;
*it = sum%10;
}
if(flag) digits.insert(digits.begin(), flag);
return digits;
}
};