Skip to content

LeetCode题解:66. 加一,新数组求和再翻转,JavaScript,详细注释 #133

@chencl1986

Description

@chencl1986

原题链接:https://leetcode-cn.com/problems/plus-one/

解题思路:

  1. 倒序遍历原数组,将数组第一位加1,如果需要进位,则下一位继续加1,以此类推。
  2. 每次求和的结果,都push到新数组中。遍历完成时,新数组存储的就是最终结果。
  3. 将新数组翻转之后,作为结果返回。
/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function (digits) {
  let plus = 1 // 用于加1的数量,当前位数与其之和大于10时,需要设置其为1
  let sum = 0 // 缓存当前值的计算结果
  // 用于缓存计算的最终结果。
  // 为了避免之后一位之和超过10需要进位,因此倒序保存结果。
  // 求和完成之后进行翻转。
  let newArr = []

  // 加法从最后一位开始进行,因此从尾部开始遍历数组
  for (let i = digits.length - 1; i >= 0; i--) {
    // 对当前位求和
    sum = digits[i] + plus
    // sum有可能超过9,因此保存新值时需要取余
    newArr[digits.length - i - 1] = sum % 10
    // 如果sum>=10,下一位需要继续加1
    plus = sum >= 10 ? 1 : 0
  }

  // 完成求和之后还有值,说明需要进位,因此向新数组存入1
  if (plus === 1) {
    newArr.push(1)
  }

  // newArr的结果真实值相反,需要翻转
  return newArr.reverse()
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions