Straight thinking java add 1 solution


  • 0
    V

    public class Solution {

    public int[] plusOne(int[] digits) {
    
        int add = 0;
        int len = digits.length;
        
        if(len == 0){
            int[] r = {1};
            return r;
        }
        
        if(digits[len - 1] == 9){
            digits[len - 1] = 0;
            add = 1;
           for(int i = len - 2; i >= 0; i--){
               if(digits[i] == 9 && add == 1){
                   digits[i] = 0;
                   add = 1;
               }else{
                 digits[i] = digits[i] + add;
                 add = 0;
               }
           }
           
           
           if(digits[0] == 0){
               int[] r = new int[len + 1];
                   r[0] = 1;
                   for(int j = 0; j < len; j++){
                       r[j + 1] = digits[j];
                   }
                   return r;
           }else{
               return digits;
           }
        
        }else{
            digits[len - 1] = digits[len - 1] + 1;
            return digits;
        }
        
    }
    

    }


Log in to reply
 

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