Friday, November 21, 2014

[LeetCode] 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.
思路:
又是逐位加法,和Add Two Numbers以及Add Binary两题类似。需要注意最低最高位的顺序以及进位的处理。


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        int carry = 1;
        vector<int> res(digits.size(),0);
        for(int i=digits.size()-1; i>=0; i--) {
            carry += digits[i];
            res[i] = carry%10;
            carry /= 10;
        }
        if(carry) res.insert(res.begin(),1);
        return res;
    }
};

No comments:

Post a Comment