FE-Interview
FE-Interview copied to clipboard
大数计算如何实现
扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

const add = (num1, num2) => {
// 获取最大长度
const len = Math.max(num1.length, num2.length);
// 补0
num1 = num1.padStart(len, 0);
num2 = num2.padStart(len, 0);
let flag = 0,esult = ``,temp = 0;
for(let i=len-1; i>=0; i--){
temp = flag + parseInt(num1[i]) + parseInt(num2[i])
result = (temp%10) + result
flag = parseInt(temp/10)
}
// 判断是否进位
return result = (flag === 1 ? '1' : '') + result;
}
const n1 = "9007199254740990"
const n2 = "1229007199254740993443"
add(n1, n2);
// "1229016206453995734433"
let n1 = BigInt('111111111111111111111111111111111111111')
let n2 = 222222222222222222222222222222222222222n
console.log(n1 + n2, n1 * n2, n1 - n2);
var addStrings = function(num1, num2) {
if (+num1 === 0) return num2
if (+num2 === 0) return num1
const arr1 = num1.split('')
const arr2 = num2.split('')
let res = ''
let flag = 0
while (arr1.length || arr2.length || flag) {
const a = arr1.length ? +arr1.pop() : 0
const b = arr2.length ? +arr2.pop() : 0
const s = a + b + flag
const t = s % 10
flag = s >= 10 ? 1 : 0
res = t + res
}
return res
};
function addStrings(num1: string, num2: string): string {
let i = num1.length - 1, j = num2.length - 1, add = 0;
const ans: number[] = [];
while(i >= 0 || j >= 0 || add!= 0) {
const x = i >= 0 ? Number.parseInt(num1.charAt(i), 10) : 0;
const y = j >= 0 ? Number.parseInt(num2.charAt(j), 10) : 0;
const r = x + y + add;
ans.unshift(r % 10);
add = Math.floor(r / 10);
i -= 1;
j -= 1;
}
return ans.join('');
};
var addStrings = function (num1, num2) {
let aLen = num1.length - 1;
let bLen = num2.length - 1;
let remainder = 0;
let result = [];
while (aLen >= 0 || bLen >= 0 || remainder !== 0) { // 注意最后一个进位
const a = aLen >= 0 ? num1.charAt(aLen) - '0' : 0;
const b = bLen >= 0 ? num2.charAt(bLen) - '0' : 0;
const tempResult = a + b + remainder;
result.push((tempResult) % 10);
remainder = Math.floor(tempResult / 10);
aLen -= 1;
bLen -= 1;
}
return result.reverse().join('');
};
// 对应 leetCode 415 题
function addStrings(num1, num2) {
// 1. 处理为 任意一者为0
if (+num1 === 0) return num2
if (+num2 === 0) return num1
const maxLen = Math.max(num1.length, num2.length)
// 2. 开头补充 0
num1 = num1.padStart(maxLen, '0')
num2 = num2.padStart(maxLen, '0')
let result = ''
let carry = 0
// 3. 倒序遍历
for (let i = maxLen - 1; i >= 0; i--) {
const total = +num1[i] + +num2[i] + carry
carry = Math.floor(total / 10)
const rest = total % 10
result = rest + result
}
// 4. 处理最高位相加依然进位的情况 188 + 880
if (carry > 0) {
result = carry + result
}
return result
}
console.log(addStrings('188', '880'))