Share my 0ms clean java code


  • 0
    Z
    public int[] plusOne(int[] digits) {
            
            int length = digits.length;
            //in case we need to add a digit
             int[] res = new int[length+1];
            if(length<1){int[] newres = {1};return newres;}
           
            
            for(int i=length-1;i>=0;i--){
               if(digits[i]==9){digits[i]=0;}
               else {digits[i]++;return digits;}
            }
            
            //add an digit
            if(digits[0]==0){
                res[0] = 1;
            }
        return res; 
        }
    

  • 0
    Z

    Do you copy the array digits to res?


  • 0
    Z

    @ZhijianChen No you don't have to, since it's "plus one", there is only one case that you need to add a digit, namely 9999...9 + 1 = 10000...0.


Log in to reply
 

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