O(n) worst case solution in java


  • 0
    P
    class Solution {
        public int[] plusOne(int[] digits) {
           int num = 0;
            if(digits[digits.length-1]!=9) {
                digits[digits.length-1] =  digits[digits.length-1] + 1;
                return digits;
            }
            int len = digits.length-1;
            do {
                num = digits[len];
                digits[len] = (num + 1) % 10;
                len--;
            }while(len>=0 && num == 9);
    
            if(len<0 & num == 9) {
                int [] newArr = new int[digits.length+1];
                newArr[0] = 1;
                return newArr;
            }
            return digits;
        }
    }
    

Log in to reply
 

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