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.
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
if(digits.size() == 0)
return digits;
int carry = 0;
for(int i = digits.size()-1; i >=0 ; -- i)
//如果使用的是size_t就是无符号的,如果减一了,那么就是一个大数而不是负数,所以越界,老是这个出错
{
int sum = digits[i] + carry ;
if(i == digits.size()-1)
sum += 1;//只有最后一位才加1
if(sum >= 10)
{
sum -= 10;
digits[i] = sum;
carry = 1;
}
else
{
digits[i] = sum;
carry = 0;//注意要重新置carry为0不然后面的最高进位判断是错得。
break;
}
}
if( carry == 1)
{
digits.insert(digits.begin(), 1);
}
return digits;
}
};