Nuggets team number online, help you Offer rimmon! Click to see details

I. Topic Description:

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 the array, and only a single digit is stored for each element of the array.

You can assume that the integer does not start with zero except 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 <= 100Copy the code

Ii. Thinking analysis:

  • String(parseInt(digits.join('')) + 1).split('');At first we did this, but the numbers lost their accuracy
  • So we’re going to iterate, if the last digit is 9, we’re going to set it to 0, and we’re going to keep going until it’s not 9.
  • If all are 9, add a 1 to the front of the array
  • If the last digit is not 9, then the last digit is +1 and the value is returned
  • You can also use BigInt

Three, AC code

/** * @param {number[]} digits * @return {number[]} */ var plusOne = function(digits) { for(let i = digits.length -1; i >= 0; i--){ if(digits[i] === 9){ digits[i] = 0 }else{ digits[i]++ return digits } } if(digits[0] == 0) digits.unshift(1) return digits; }; Execution time: 84 ms Memory: 37.9 MBCopy the code

Four,

  • Of course, there’s more than one way to do this, so here’s BigInt;
/** * @param {number[]} digits * @return {number[]} */ var plusOne = function(digits) { const numStr = digits.join('') Const resBig = numBig + BigInt(1) const resBig = numBig + BigInt(1 resBig.toString().split('').map(Number) };Copy the code

For reference only

Refer to the topic

  • Force button (LeetCode)