The title

LeetCode problem 66. Add one associative type: array

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: 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] Hint: 1 <= digits. Length <= 100 0 <= digits[I] <= 9Copy the code

Time to solve the problem.

class Solution {
    public int[] plusOne(int[] digits) {
        
        
        
        
    }

}

Copy the code

The method input parameters are given above to complete the answer.

Subject analysis

  1. Solving this problem and primary school math feeling is the same, every ten into one, otherwise in this position can add one
  2. So we can write a recursive method that starts at the last digit, subtracts by one on every decimal digit, or adds by one to return the array
  3. The critical condition is that the current position does not have a decimal and returns directly. Or if the current subscript is 0, a new array is created and the first position 1 is returned

Answers to analysis

This article only analysis I do the idea, only for reference, to understand a solution to the idea, other kinds of ideas to do the problem please access the Internet.

Answer successful: Execution time :0 ms, beat 100.00% Java user memory consumption :36.9 MB, beat 53.68% Java users

Class Solution {public int[] plusOne(int[] digits) {return plusEveryOne(digits, digits.length-1); } public int[] plusEveryOne(int[] nums, int index) {if (nums[index]! = 9) { nums[index] += 1; return nums; } else {// If the current position is 9, but not the first position, the current is 0, subscript 1, recursive call if (index! = 0) { nums[index] = 0; index--; return plusEveryOne(nums, index); } else {int[] res = new int[nums.length + 1];} else {int[] res = new int[nums.length + 1]; res[0] = 1; return res; }}}}Copy the code