Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chencl1986 opened this issue Sep 19, 2020 · 0 comments
Open

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

chencl1986 opened this issue Sep 19, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

chencl1986 commented Sep 19, 2020

原题链接: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 // 返回结果
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant