题目:
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.
解答:
只有一种情况会导致位数发生改变,就是全部都是9的时候
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int size = digits.size();
int pos = size - 1;
while(pos >= 0)
{
if(digits[pos] == 9)
digits[pos--] = 0;
else
{
digits[pos]++;
break;
}
}
if(digits[0] == 0)
{
digits[0] = 1;
for(int j = 1;j < size; ++j)
digits[j] = 0;
digits.push_back(0);
}
return digits;
}
};