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) {
vector<int> res(digits);
int val = 0;
int carry = 1;
for (int i = digits.size() - 1; i >= 0; --i) {
val = (digits[i] + carry) % 10;
carry = (digits[i] + carry) / 10;
res.at(i) = val;
}
if (carry == 1)
res.insert(res.begin(), 1);
return res;
}
};