Java 1ms solution, hope to improve


  • 0
    K
    public class Solution {
        public int[] plusOne(int[] digits) {
            boolean[] change = new boolean[digits.length];
            int create = 0;
            int i = digits.length - 1;
            change[i] = true;
            while(digits[i] == 9 && i >= 1){
                i--;
                change[i] = true;    
            }
            
            if(i == 0 && digits[i] == 9) create = 1;
            int[] result = new int[digits.length + create];
            for(int j = digits.length - 1; j >= 0; j--){
                if(change[j])
                    result[j + create] = (digits[j] + 1) % 10;
                else
                    result[j + create] = digits[j];
            }
            if(create == 1) result[0] = 1;
            
            return result;
        }
    }

Log in to reply
 

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