chencl1986/Blog

LeetCode题解:66. 加一,BigInt,JavaScript,详细注释

Opened this issue · 0 comments

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

解题思路:

  1. 将数组转换为数字,加1之后再转换为数组即可。
  2. 但测试用例[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]超出了Number的范围,直接转换会报错。
  3. 使用BigInt计算,即可解决。BigInt 是一种内置对象,它提供了一种方法来表示大于 253 - 1 的整数。这原本是 Javascript中可以用 Number 表示的最大数字。BigInt 可以表示任意大的整数。
/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
  const numStr = digits.join('') // 将数组转换为字符串
  const bigInt = BigInt(numStr) // 将字符串转换为BigInt类型
  const result = bigInt + 1n // 加1,一个整数字面量后面加 n 的方式定义一个 BigInt
  const resultStr = new String(result) // 将数字转换为字符串
  const resultStrArr = resultStr.split('') // 将字符串转换为数组
  const resultNumArr = resultStrArr.map(num => Number(num)) // 将字符串数组转换成数字数组

  return resultNumArr // 返回结果
};