Recursive Java solution


  • 0
    public class Solution {
        
        public int[] func(int[] A, int n){
            if(n==0){
                int l=A.length;
                int[] digits = new int[l+1];
                digits[0]=1;
                return digits;
            }
            
            if(A[n-1]<9){
                A[n-1]++;
                return A;
            }
            else{
                A[n-1]=0;
                return func(A,n-1);
            }
            
            
        }
        
        
        
        public int[] plusOne(int[] digits) {
            int n = digits.length;
            
            digits = func(digits,n);
            return digits;
                
            
        }
    }

  • 0
    S

    public class Solution {
    public int[] plusOne(int[] digits) {
    int flag=0;
    int len=digits.length;
    flag=(digits[len-1]+1)/10;
    digits[len-1]=(digits[len-1]+1)%10;
    for(int i=2 ; i<=len ; i++){
    int a=flag+digits[len-i];
    flag=a/10;
    digits[len-i]=a%10;
    }
    if(flag == 1){
    int[] newDigits=new int[len+1];
    newDigits[0]=flag;
    for(int i=0;i<len;i++){
    newDigits[i+1]=digits[i];
    }
    return newDigits;
    }
    return digits;
    }
    }


Log in to reply
 

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