[LeetCode] 66. Plus One

Problem

Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

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

Example 2:

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

Explanation

  1. Loop through the array from the last index element, if it is less than 9, then we can add one to it, and return;

    1
     [1, 2, 3] => [1, 2, 4]
    
  2. Else if it is 9, then we set this element to 0, and continue to check the next element.

    1
     [1, 2, 9] => [1, 3, 0]
    
  3. After the loop, meanning that it’s still not returning and the first index element is 0. Then, we create a new array have the first element set to 1, and starts from the second elment, it has all the same elements as the digits array.

    1
     [9, 9, 9] => [1, 0, 0, 0]
    

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
    public int[] plusOne(int[] digits) {
        int n = digits.length;
        for (int i = digits.length - 1; i >= 0; --i) {
            if (digits[i] < 9) {
                ++digits[i];
                return digits;
            }
            digits[i] = 0;
        }
        int[] res = new int[n + 1];
        res[0] = 1;
        return res;
    }
}