My Java answer. Can it be made more efficient?


  • 0
    J
    public class Solution {
        public int[] plusOne(int[] digits) {
            int carry = 0;
            digits[digits.length-1] += 1;
            for (int i=digits.length-1; i>=0; i--) {
                if (digits[i]+carry == 10) {
                    digits[i] = 0;
                    carry = 1;
                } else {
                    digits[i] += carry;
                    carry = 0; 
                }
            }
            if (carry !=0) {
                int [] ugh = new int[digits.length+1];
                ugh[0] = carry;
                for (int j =0; j<digits.length; j++) {
                    ugh[j+1] = digits[j];
                }
                return ugh;
            }
            return digits;
            
        }
    }

  • 0
    F

    You could use while loop instead of for loop, because you won't need to go further as soon as your carry is zero.


Log in to reply
 

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