How to use JavaScript BigInt and Number.prototype.toString to handle the super large integer problems All In One
如何使用 JavaScript
BigInt
和Number.prototype.toStringg
处理超大整数问题
errors
function plusOne(digits: number[]): number[] {
let n = parseInt(digits.join(``));
return `${n + 1}`.split(``).map(Number);
};
// // 大数相加超出 JavaScript 中的最大安全整数 (2**53 – 1) 最大值 bug ❌
solutions
function plusOne(digits: number[]): number[] {
const arr: number[] = digits;
// 进位
let inc = 1;
for (let i = arr.length - 1; i >= 0; i--) {
const n = arr[i] + inc;
if(n >= 10 && inc) {
arr[i] = n - 10;
inc = 1;
} else {
arr[i] = n;
inc = 0;
}
}
// 最高一位进位
if(inc) {
arr.unshift(inc);
}
return arr;
};
function plusOne(digits: number[]): number[] {
let rest: number = 1;
let temp: number = 0;
for(let i = digits.length -1; i >= 0; i--) {
temp = digits[i] + rest;
rest = temp > 9 ? 1 : 0;
digits[i] = temp > 9 ? 0 : temp;
}
// 插入 1 进位
if(rest) {
digits.unshift(1);
}
return digits;
};
function plusOne(digits: number[]): number[] {
return (BigInt(digits.join(``)) + BigInt(1)).toString().split(``).map(Number);
};
demos
function plusOne(digits: number[]): number[] {
let rest: number = 1;
let temp: number = 0;
for(let i = digits.length -1; i >= 0; i--) {
temp = digits[i] + rest;
rest = temp > 9 ? 1 : 0;
digits[i] = temp > 9 ? 0 : temp;
}
// 插入 1 进位
if(rest) {
digits.unshift(1);
}
return digits;
};
// BigInt ❓ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
// 大数相加超出 JavaScript 中的最大安全整数 (2**53 – 1) 最大值 bug ❌
/*
6145390195186705543 + 1
// 6145390195186705000
*/
// function plusOne(digits: number[]): number[] {
// let n = parseInt(digits.join(``));
// return `${n + 1}`.split(``).map(Number);
// };
/*
Wrong Answer
71 / 111 testcases passed
Input
digits =
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
*/
https://leetcode.com/problems/plus-one/description/