本题题目要求如下:
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.
这是一道简单题,其实就是考下对进位的处理,因为只加了1,所以要是第一位不进位就可以直接结束了例如111转化成112,相当简单。。我的实现方法就是检测有多少个连续的9,然后把这些9都变成0,如果位数不够,就加一位,如果够了,就在下一位加一。。
代码如下:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int start = digits.size()-1;
while (digits[start] == 9) {
digits[start] = 0;
--start;
if (start < 0) {
digits.insert(digits.begin(), 0);
start = 0;
}
}
digits[start] = digits[start] + 1;
return digits;
}
};