Java Solution (Time Complexity O(n))


  • 0
    C
    class Solution {
        public int[] plusOne(int[] digits) {
    
            ArrayList<Integer> intList = new ArrayList<Integer>(digits.length);
            for (int i=0; i<digits.length; i++)
            {
                intList.add(digits[i]);
            }
    
            int carryForward = 0;
            int lastelmt = intList.size() - 1;
            for (int i = lastelmt; i >=0; i--){
                int num = intList.get(i);
                
                if (i == lastelmt){
                    num = num + 1;
                }else{
                    num = num + carryForward;
                }
                
                if (num >= 10){
                    intList.set(i,num%10);
                    carryForward = 1;
                }else{
                    carryForward = 0;
                    intList.set(i,num);
                }
                
                if (i==0 && carryForward == 1){
                    intList.add(0,1);
                }
            }
    
            int[] result = new int[intList.size()];
            for (int i=0; i < result.length; i++){
                result[i] = intList.get(i).intValue();
            }
            
            return result;
        }
    }
    

Log in to reply
 

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