0ms Java simple and clear


  • -1
    C
    public class Solution {
        public int[] plusOne(int[] digits) {
            digits[digits.length - 1] += 1;
            
            int carry = 0;
            for (int i = digits.length - 1; i >= 0; i--) {
                int tmp = digits[i] + carry;
                if (tmp >= 10) {
                    digits[i] = 0;
                    carry = 1;
                } else {
                    digits[i] = tmp;
                    carry = 0;
                }
            }
            
            if (carry == 1) {
                return increase(digits);
            }
            return digits;
        }
        
        private int[] increase(int[] digits) {
            int[] result = new int[digits.length + 1];
            result[0] = 1;
            for (int i = 1; i < result.length; i++) {
                result[i] = digits[i-1];
            }
            return result;
        }
    }

Log in to reply
 

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