Question

link

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Stats

Frequency 2
Difficulty 1
Adjusted Difficulty 1
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is an easy question.

My code

public int[] plusOne(int[] digits) {
    int n = digits.length - 1;
    while (n != -1 && digits[n] == 9) {
        n--;
    }
    if (n != -1) {
        // a non-9 number is found. change it.
        digits[n] ++;
        for (int i = n + 1; i < digits.length; i ++) {
            digits[i] = 0;
        }
        return digits;
    } else {
        int[] newD = new int[digits.length + 1];
        newD[0] = 1;
        for (int i = 1; i < newD.length; i ++) {
            newD[i] = 0;
        }
        return newD;
    }
}