The front end of a plus leetcode 66. Algorithm

# Front end of the algorithm leetcode 66. plus one

Title Description

Given a non-negative integer nonempty array of integers represented, on the basis of the number plus one.

Most significant digit stored in the first array, each element of the array stores only a single digit.

You may assume that in addition to the integer 0, the integer does not begin with a zero.

Example 1:

输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。

Example 2:

输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。

66. plus one

Overview

Consider the case can carry, create an empty array, the array length is the length + 1 incoming, and then return to the first bit of this array to +1

prompt

Resolve

A Solution

Just add a title meaning, which means it's only two cases, ends with a 9 or 9

The last one is 9 plus a carry when 0, ending the cycle if the operation does not appear Carry

Consider the special circumstances 99,99999, etc., manually create an array fill 0

Solution two

From the back in turn to each count plus one, plus one is greater than 10 pairs modulo 10, all the way to the head of the array when the i===0array head can be added to a 1

algorithm

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
  for (let i = digits.length - 1; i >= 0; i--) {
    digits[i]++
    digits[i] = digits[i] % 10
    if (digits[i] !== 0) return digits
  }
  digits = new Array(digits.length + 1)
  for (let i = 1; i < digits.length; i++) {
    digits[i] = 0
  }
  digits[0] = 1
  return digits
  // 解法2
  // for (let i = digits.length - 1; i >= 0; i--) {
  //   digits[i]++
  //   if (digits[i] >= 10) {
  //     digits[i] = digits[i] % 10
  //     if (i === 0) {
  //       digits.unshift(1)
  //       break
  //     }
  //   } else {
  //     break
  //   }
  // }
  // return digits
};

Incoming [1,2,3]operating results

[1,2,4]

Results of the

执行用时 :44 ms, 在所有 javascript 提交中击败了100.00% 的用户
内存消耗 :33.7 MB, 在所有 javascript 提交中击败了33.81%的用户

Guess you like

Origin www.cnblogs.com/moshuying/p/11828953.html