[LeetCode 66] Add one Given a non-negative integer represented by a non-empty array of integers, add one to the number. The highest digit is stored in the first position of the array, and each element in the array only stores a single number.

learning target:

Goal: proficiently use the knowledge learned in Java


Subject content:

The content of this article: Implementation in Java: plus one


Title description

Given a non-negative integer represented by a non-empty array of integers, add one to the number.

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

You can assume that in addition to the integer 0, this integer does not start with a zero.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The input array represents the number 123.

Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The input array represents the number 4321.

Example 3:

Input: digits = [0]
Output: [1]

Problem-solving ideas

I just saw this question is quite daunting. I probably got the first idea after I understood it. The first idea was to convert the array to an integer, add one, and convert to an array. This idea is not difficult, but There is actually a {0,0} in the Likou use case. My program calculates it as {1}, but the correct answer is {0,1}.

Can only change the way of thinking:

Traverse the array from back to front. If the number encountered is not 9, add one and return to the array. If it is 9, assign the current bit to 0 and continue to loop to the previous bit. If it is not 9, add one to return. Keep reciprocating, knowing to traverse all the array elements, when the array elements are all 9, then create a new array with a length larger than the original array, the first bit is assigned 1, and the others are 0;

Implementation code

public class Practice_01 {
    
    
    public static void main(String[] args) {
    
    
        //给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。最高位数字存放在数组的首位, 数
        //组中每个元素只存储单个数字。(注意:你要防止的是第一个数字是9或者最后一个是9哈!这种情况会有进位滴)
        int[] a={
    
    1,1,9};
        System.out.println(Arrays.toString(plusOne(a)));
    }
    public static int[] plusOne(int[] digits){
    
    
        for (int i = digits.length - 1; i >= 0; i--) {
    
    
            if (digits[i] != 9) {
    
    
                //如果不是9直接加一返回
                digits[i]++;
                return digits;
            }
            digits[i] = 0;//如果当前位是9,则需要进位,当前位赋值为0,前一位加一
        }
        //跳出for循环,说明数字全部是9
        int[] result = new int[digits.length + 1];
        result[0] = 1;
        return result;
    }
}

operation result

[1, 2, 0]

Guess you like

Origin blog.csdn.net/zhangxxin/article/details/113118880