66. Plus One

1. Description

Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.

2. Example

Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

Example 3:
Input: digits = [0]
Output: [1]

3. Constraints

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9

4. Solutions

Reverse Iter

n = digits.size()
Time complexity : O(n)
Space complexity : O(1)

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        int last_nine_index = digits.size();
        for (int i = digits.size() - 1; i >= 0; --i) {
            if (digits[i] == 9) {
                last_nine_index = i;
            } else {
                break;
            }
        }

        vector<int> plus_one_digits(digits);
        if (last_nine_index > 0) {
            ++plus_one_digits[last_nine_index - 1];
            for (int i = last_nine_index; i < plus_one_digits.size(); ++i) {
                plus_one_digits[i] = 0;
            }
        } else {
            plus_one_digits.insert(plus_one_digits.begin(), 1);
            for (int i = 1; i < plus_one_digits.size(); ++i) {
                plus_one_digits[i] = 0;
            }
        }

        return plus_one_digits;
    }
};
Last updated:
Tags: Array
comments powered by Disqus