Plus One

Question (LC.66)

Analysis

Easy array question that needs some math to solve. Warm up before the real question. Practice speed and bug free.

Code

/**
 * The heart of this problem is carry. possibly create a new array with one more size.
 * The upper bound is O(n). But the constant can be reduced.
 */
public static int[] plusOne(int[] digits) {

    for (int rp = digits.length - 1; rp >=0; rp--) {
        if (digits[rp] < 9) {
            digits[rp]++;
            return digits;
        } else {
            digits[rp] = 0;
        }
    }

    int[] newArr = new int[digits.length + 1];
    newArr[0] = 1;
    return newArr;
}

results matching ""

    No results matching ""