Interview 150

Plus One

Problem
LC 66
File
interview150_LC66PlusOne.java
Path
pkg5leetcode/interview150/interview150_LC66PlusOne.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC66PlusOne.java
Approach
Add from end with carry; prepend 1 if overflow.
Complexity
Time O(n), Space O(1) excluding output

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC66PlusOne.java
1package pkg5leetcode.interview150;2 3/*4 * Plus One | LC 665 * APPROACH: Add from end with carry; prepend 1 if overflow.6 * COMPLEXITY: Time O(n), Space O(1) excluding output7 */8public class interview150_LC66PlusOne {9    static int[] plusOne(int[] digits) {10        for (int i = digits.length - 1; i >= 0; i--) {11            if (digits[i] < 9) { digits[i]++; return digits; }12            digits[i] = 0;13        }14        int[] res = new int[digits.length + 1];15        res[0] = 1;16        return res;17    }18 19    public static void main(String[] args) {20        check(java.util.Arrays.equals(plusOne(new int[]{1, 2, 3}), new int[]{1, 2, 4}), "case1");21        check(java.util.Arrays.equals(plusOne(new int[]{9}), new int[]{1, 0}), "case2");22        System.out.println("all tests passed");23    }24 25    static void check(boolean cond, String name) {26        if (!cond) throw new AssertionError("FAILED: " + name);27        System.out.println("  PASS " + name);28    }29}