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.

Solution

public class Solution {
    public int[] plusOne(int[] digits) {
        int carry = 1;
        for(int i = 0; i < digits.length; i++) {
            int num = digits[digits.length - 1 - i];
            if(carry != 0) {
                num += 1;
                carry = (num == 10) ? 1 : 0;
                digits[digits.length - 1 - i] = num % 10;
            } else {
                break;
            }
        }

        if(carry == 1) {
            int[] newCentuary = new int[digits.length + 1];
            for(int i = 0; i < newCentuary.length; i++) newCentuary[i] = 0;
            newCentuary[0] = 1;
            return newCentuary;
        } else {
            return digits;
        }
    }
}

results matching ""

    No results matching ""