LeetCode——66. Plus one

Given a non-negative integer represented by an array of integer, Add one based on the basis.

The highest digit is stored in the first place of the array, and each element in the array stores only one number.

You can assume that this integer will not start with zero except for the integer 0.

example 1:

输入: [1,2,3]
Output: [1,2,4]
Explanation: The input array represents the number 123. 

样2:

输入: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The input array represents the number 4321. 

解解思维

1, traversing from the last digit of the array (excluding the first digit), if the latter element is greater than or equal to 10, the previous one is incremented by 1, and the element is decremented by 10. (already in place).

2, judge whether the first digit is greater than or equal to 10, and if it is greater than or equal to 10, give a signal (isOver).

3, If the information is received (isOver) indicates that the first element needs to be carried, then an array with a length greater than the original array is created. The first bit of the array is 1, and the remaining elements are copied from the original array.

Code

class Solution {
    public int[] plusOne(int[] digits) {
        int N = digits.length;
        Boolean isOver  = false;

        digits[N-1] = digits[N-1] + 1;
        for (int i = N - 1; i > 0; i--) {
            if (digits[i] >= 10) {
                digits[i-1] = digits[i-1] + 1;
                digits[i] = digits[i] - 10;
            }
        }
        if (digits[0] >= 10) {
            isOver = true;
        }
            
        if (isOver) {
            int[] news = new int[N+1];
            news[0] = 1;
            digits[0] = digits[0] - 10;
            for (int i = 1; i < news.length; i++) {
                news[i] = digits[i-1];
            }
            return news;
        }
        return digits;
    
    }
}