Plus One

Given a number represented as an array of digits, plus one to the number.

Solution: follow what we usually do for addition... 

The following code passes LeetCode OJ Large Judge.


class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        bool add = true;
        int i = digits.size() - 1;
        while(add && i >= 0) {
            if(digits[i] < 9) {
                digits[i]++;
                add = false;
            }
            else {
                digits[i] = 0;
                i--;
            }
        }
        if(add && i < 0) digits.insert(digits.begin(), 1);
        return digits;
    }
};

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design