LeetCode 150 classic interview questions -- plus one (simple)

1. Topic

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

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

You can assume that this integer will not start with a zero other than the integer 0.

2. Examples

Example 1:

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

 Example 2:

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

 Example 3:

input: digits = [0]
output: [1]


 3. Ideas

This question looks relatively simple, but there are also pitfalls.

The first point, when the last digit is 9, a carry is required when adding one.

Secondly, when the first digit is 9, adding one needs to recreate a new array, and assign a value of 1 to the first digit of the new array.

4. Code

class Solution {
    public int[] plusOne(int[] digits) {
         if (digits.length==1 &&digits[0]==0){
            digits[0] = 1;
        }else {
            digits[digits.length-1]+=1;
        }
         for (int i= digits.length-1;i>=0;i--){
            if (digits[i]==10){
                if (digits.length ==1 || i == 0){
                    digits = new int[digits.length+1];
                    digits[0]=1;
                    break;
                }
                digits[i] =0;
                digits[i-1]+=1;
            }
        }
        return digits;
    }
}

 Will it? Try to challenge the next question! ♪(^∀^●)ノシ(●´∀`)♪

LeetCode 150 classic interview questions -- plus one (simple)_Alphamilk's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/dogxixi/article/details/132340804