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.
首先考虑有以下几种情况:
1899
1999
9999
如果是前两种情况,则只需要考虑前一个加法是否有进位,而最后一个需要考虑计算完之后,在首位插入进位1;
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int flag = 1;
for (int i = digits.size() - 1; i >=0; --i)
{
if (1 == flag)
{
if (digits[i] + flag >= 10)
{
digits[i] = (digits[i] + flag) % 10;
flag = 1;
}
else
{
digits[i] = digits[i] + flag;
flag = 0;
}
}
else
return digits;
}
if (1 == flag)
digits.insert(digits.begin(),1);
return digits;
}
};