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<int> plusOne(vector<int> &digits) {
vector<int> 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<int> plusOne(vector<int> &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;
}
时间: 2024-10-16 23:12:30