Plus One

Problem

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.

Example: Given [2, 3] return [2, 4]; Given [1, 9] return [2, 0].

Solution

public class Solution {
    public int[] plusOne(int[] digits) {
        int len = digits.length;
        for (int i = len - 1; i >= 0; i--) {
            if (digits[i] != 9) {
                digits[i]++;
                break;
            }
            digits[i] = 0;
        }
        if (digits[0] == 0) {
            int[] newArray = new int[len + 1]; //We don't have to copy the array, cause it must be [1, 0, 0, ...]
            newArray[0] = 1;
            return newArray;
        }
        return digits;
    }
}

Analysis

The hard part of this problem is only some corner cases
Like when the last digit is 0 or the number add one more significant digit
The solution above handles all the corner cases pretty well

results matching ""

    No results matching ""