添加图片注释,不超过 140 字(可选)
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('');
};
页面更新:2024-03-28
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号