My Accepted Java Solution


  • 2
    J

    Hi everyone, this is my accepted Java solution. I used a while loop here so that I don't need to go through the entire array if it's not necessary. Basically, the code will start from the last index of the array and go backwards. if there is a carry-over value, then it will keep going, otherwise it will stop. After the traversing is done, it will check if the first digit is zero (9999 + 1 = 0000) and handle that case. Hope this helps :)

    public int[] plusOne(int[] digits) {
        boolean carry = true;
        int index = digits.length - 1;
        while (carry && index > -1) {
            if (digits[index] == 9) {
                digits[index] = 0; // carry remains true
            } else {
                digits[index] += 1;
                carry = false;
            }
            index--;
        }
        if (digits[0] == 0) {
            int[] result = new int[digits.length + 1];
            result[0] = 1;
            for (int i = 1; i < digits.length; i++) {
                result[i] = digits[i - 1];
            }
            return result;
        }
        return digits;
    }

  • 0
    P

    Base on your code, I modified it to recursive version.
    But recursive version is less efficient and space complexity is O(n).

    	public int[] plusOne(int[] digits) {
    	if (digits.length == 0) {
    		return new int[] { 1 };
    	}
    
    	for (int i = digits.length - 1; i >= 0; i--) {
    		digits[i] = digits[i] + 1;
    		if (digits[i] == 10) {
    			int[] original = plusOne(Arrays.copyOfRange(digits, 0, i));
    			int[] after = Arrays.copyOf(original, original.length + 1);
    			after[after.length - 1] = 0;
    			return after;
    		}
    		else {
    			return digits;
    		}
    	}
    
    	return null;
    }

  • 0
    Z

    here is my AC solution

        public int[] plusOne(int[] digits) {
            for (int i = digits.length - 1; i >= 0; i--) {
                digits[i] = digits[i] + 1;
                if (digits[i] == 10) {
                    digits[i] = 0;
                } else {
                    return digits;
                }
            }
    
            int[] result = new int[digits.length + 1];
            result[0] = 1;
            return result;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.