Version I

remember when to carry digit up

public class Solution {

    //1,2,3 => 1,2,4
    //1,9 => 2,0
    //0 => 1
    //1,9,9 => 2,0,0

    public int[] plusOne(int[] digits) {
        //validate input
        if (digits == null || digits.length == 0) return digits;

        //variable
        int carry = 0;

        //loop through the array
        for (int i = digits.length - 1; i >= 0; --i) {
           int curr = digits[i];

           if (i == digits.length - 1) {
               curr++;
           }

           if (carry == 1) {
               curr++;
               carry = 0;
           }

           if (curr >= 10) {
               curr = 0;
               carry = 1;
           }

           digits[i] = curr;

        }

        if (carry != 0) {
            int[] result = new int[digits.length + 1];

            for (int i = 0; i < digits.length; ++i) {
                result[i + 1] = digits[i];
            }
            result[0] = 1;

            return result;
        }

        return digits;
    }
}

Version II - improve

the for loop needs to continue, only when the digits equals to 9

check whether the highest bit equals to 0 at last, if it's, create a new array

public class Solution {

    //1,2,3 => 1,2,4
    //1,9 => 2,0
    //9 => 1,0
    //1,9,9 => 2,0,0

    //oneMore

    public int[] plusOne(int[] digits) {
        //validate input
        if (digits == null || digits.length == 0) return digits;

        for (int i = digits.length - 1; i >= 0; --i) {
            digits[i]++;

            if (digits[i] <= 9) {
                return digits;
            } else {
                digits[i] = 0;
            }
        }


        int[] newDigits = new int[digits.length + 1];
        newDigits[0] = 1;

        return newDigits;

    }
}

results matching ""

    No results matching ""