Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
题意:给定一个数组表示的非负整数,对这个数加一
思路:从数组尾开始判断加一后会不会进位,直到不会进位,若最高位进位,则头插1。
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int len = digits.size() - 1;
while (len >= 0 && ++digits[len] == 10) {
digits[len] = 0;
len--;
}
if (len < 0) {
digits.insert(digits.begin(), 1);
}
return digits;
}
};