Topic describes

This is 66 on LeetCode. Plus one, difficulty is easy.

Key words: array, threshold

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

The highest digit is stored at the beginning of an array, where each element stores only a single digit.

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

Example 1:

Input: digits = [1,2,3] output: [1,2,4] explanation: input array represents the number 123.Copy the code

Example 2:

Input: digits = [4,3,2,1] output: [4,3,2,2] explanation: input array represents the number 4321.Copy the code

Example 3:

Input: digits = [0] output: [1]Copy the code

Tip:

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9

Their thinking

We all know that when you add one to a number, if the number is 9, you carry it. So for arrays that use array storage (high order first).

It can be divided into three cases:

  1. No carry: i.e. the last digit isThe < 9The last digit is needed+ 1That’s it.
  2. Carry but no carry at the head: that is, any position other than the head of the array can be carried, only the current bit becomes0, the former one+ 1That’s it.
  3. Carried and carried first: The only way this can happen is if all positions in the array are digits9, you just need to create a new array that is a bit longer than before1Just, like10,100,1000,10000.
class Solution {
    public int[] plusOne(int[] digits) {
        int len = digits.length;
        // Iterate through the array from back to front
        for (int i = len - 1; i >= 0; i--) {
            int value = digits[i];
            if(value ! =9) {
                // if it is not 9, add one and return
                digits[i] ++;
                return digits;
            } else {
                // If it is 9, change to 0 and continue traversing
                digits[i] = 0; }}// The last digit is 9, so change all bits to 0, the first digit is 1
        digits = new int[len + 1];
        digits[0] = 1;
        returndigits; }}Copy the code

reference

My Github repository has been set up synchronously, click access