Original link: leetcode-cn.com/problems/pl…

Answer:

  1. Iterate backwards through the array, incrementing the first bit by 1, incrementing the next bit by 1, and so on.
  2. Each time the sum is pushed into a new array. When the traversal is complete, the new array stores the final result.
  3. The new array is flipped and returned as the result.
/ * * *@param {number[]} digits
 * @return {number[]}* /
var plusOne = function (digits) {
  let plus = 1 If the sum of the current digit is greater than 10, set it to 1
  let sum = 0 // Caches the calculation result of the current value
  // Used to cache the final result of the calculation.
  // Save the result in reverse order to avoid the need to carry more than 10 bits.
  // After summing, flip over.
  let newArr = []

  // The addition starts at the last digit, so the array is iterated from the tail
  for (let i = digits.length - 1; i >= 0; i--) {
    // Sum the current bit
    sum = digits[i] + plus
    // The sum may exceed 9, so the new value will need to be mod Ed
    newArr[digits.length - i - 1] = sum % 10
    // If sum>=10, the next digit needs to be incremented by 1
    plus = sum >= 10 ? 1 : 0
  }

  // Add 1 to the new array
  if (plus === 1) {
    newArr.push(1)}// The result of newArr is the opposite and needs to be reversed
  return newArr.reverse()
};
Copy the code