题目:
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.
思路:利用vector存数一个数digits,然后实现模拟数字加1的操作
Attention: 综合考虑十位数进行加1操作的过程,满10才进位,而且是循环进行的。
AC Code:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
//利用vector存数一个数digits,然后实现模拟数字加1的操作
int sized = digits.size();
for(int i = sized-1; i >= 0; i--)
{
digits[i] +=1;
if(digits[i] < 10)
break;
else
{
digits[i] %= 10;
//进位要分情况讨论
if(i==0)
digits.insert(digits.begin(),1);
//else
// digits[i-1] +=1;(此句多余)循环加一:如果低位有进位,循环会继续,然后进位加到前一位上;如果没有,将退出加一循环。
}
}
return digits;
}
};