Leetcode Plus One

OpenSoucre發表於2014-03-28

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.

    vector<int> plusOne(vector<int> &digits) {
        int carry = 1;
        for(int i = digits.size() -1 ; i >= 0; -- i){
            
            int value = digits[i] +carry;
            carry = value/10;
            digits[i] = value%10;
        }
        if(carry == 0) return digits;
        else{
            vector<int> res(digits.size()+1);
            res[0] = carry;
            copy(digits.begin(),digits.end(),res.begin()+1);
            return res;
        }
    }

 

相關文章