[LeetCode] 66. Plus One

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.

Thought process:
We don't know if the result array will have the same length as the input array. Therefore, we can use a list to hold the sum, and copy the numbers over to the result array.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    public int[] plusOne(int[] digits) {
        List<Integer> list = new ArrayList<>();
        int sum = digits[digits.length - 1] + 1;
        int carry = sum / 10;
        list.add(sum % 10);
        
        int i = digits.length - 2;
        while (i >= 0 || carry > 0) {
            int digit = i >= 0 ? digits[i] : 0;
            sum = digit + carry;
            list.add(sum % 10);
            carry = sum / 10;
            i--;
        }
        
        int[] result = new int[list.size()];
        for (i = 0; i < result.length; i++) {
            result[i] = list.get(list.size() - 1 - i);
        }
        return result;
    }
}

Time complexity: O(n).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee