Plus One

LeetCode #66


Description:

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.

Example:

Note

Idea:

简单,从后往前加,如果数组到头了还要再进位,就insert于数组最前面。

Code:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        vector<int> result(digits);
        int carry=1;
        for(int i=digits.size()-1; i>=0 && carry!=0; --i){
            int sum = digits[i]+carry;
            result[i] = sum%10;
            carry = sum/10;
        }
        // 要增加一个位子
        if(carry==1){
            result.insert(result.begin(), 1);
        }
        return result;
    }
};

results matching ""

    No results matching ""