Monday, May 12, 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.


If the lowest significant digit is not 9, we can just add one and return. Otherwise, we need to set it to 0 and make the next digit plus one.

C++ Code:

/*
 * func: plus_one
 * goal: plus one to a number stored in a digit vector
 * @param digits: vector storing digits of the number
 * return: digit vector after plus one
 */
vector<int> plus_one(vector<int> &digits){
    int iter = digits.size()-1;
    while(iter >= 0){
        digits[iter] = digits[iter] + 1;
        if(digits[iter] < 10){
            return digits;
        }else{
            digits[iter] -= 10;
            --iter;
        }
    }
    digits.insert(digits.begin(), 1);
    return digits;
}

Python Code:

# func: plus one on a number represented by a list
# @param digits: input digits list
# @return: digits list after plus one
def plus_one(digits):
    i = len(digits)-1
    while i >= 0:
        if digits[i] != 9:
            digits[i] += 1
            return digits
        else:
            digits[i] = 0
            i -= 1
    digits = [1] + digits
    return digits

No comments:

Post a Comment