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返回,於是有了下面的解法:
C++ code vector plusOne(vector &digits) {
vector result;
int carry = 1;
for (int i = digits.size() - 1; i >= 0; --i){
result.insert(result.begin(), (digits[i] + carry) % 10);
carry = (digits[i] + carry == 10);
}
if (carry)
result.insert(result.begin(), 1);
return result;
}
後來看到Discuss中別人的做法都是在原數組上做的,又重新審了一下題,發現題目中的“the number”指的應該是在原數組。這樣在做法上還帶來一點區別就是:發現沒有進位時即可退出循環。解法如下:
C++ code vector plusOne(vector &digits) {
int carry = 1;
for (int i = digits.size() - 1; i >= 0; --i){
if (carry)
{
digits[i] += carry;
carry = (digits[i] == 10);
digits[i] %= 10;
}
else
break;
}
if (carry)
{
digits[0] = 1;
digits.push_back(0);
}
return digits;
}