66. Plus One

Given a non-negative integer represented as anon-emptyarray 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.

class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null || digits.length == 0) return new int[0];
        Stack<Integer> stack = new Stack<>();

        int addon = 1;
        for (int i = digits.length - 1; i >= 0; i--){
            int sum = digits[i] + addon;
            stack.push(sum % 10);
            addon = sum / 10;
        }
        if (addon > 0) stack.push(addon);

        int[] ans = new int[stack.size()];
        int index = 0;
        while (!stack.isEmpty()){
            ans[index++] = stack.pop();
        }

        return ans;
    }
}

results for ""

    No results matching ""