題目:
兩個非負數的大數相加,求和
示例1:
a = "9222222222222222222229992222298569222222222222222222222111199";
b = "222222222222222222222222222222222222222222222222222222222222222222222222"
求和:
a + b = "222222222231444444444444444444452214444520789444444444444444444444333421"
考慮到JavaScript最大安全整形數字是Number.MAX_SAFE_INTEGER,也就是9007199254740991,這個最大數字是16位數,
兩個15位的大數相加之和可能超過這個數字,因此選擇14位是最安全的,
思路:
將每個數字以14位為一組進行拆分,因此可將示例中數字拆分,從后向前拆分,不足14位的單獨一組

如果每組陣列相加位數超過14位,則進制位加1,bit = 1
a[1] + b[1] = 92222222222222 + 22222222222222 = 114444444444444
將首位1去除,得14444444444444
詳細代碼
const twoBigintSum1 = (a: string, b: string): string => {
console.log(a)
console.log(b)
// 考慮到最大數為16位,`Number.MAX_SAFE_INTEGER = 9007199254740991`
// 將字串每14位拆分為一組
let i = a.length, j = b.length, res = '', bit = 0;
while(i > 0 || j > 0) {
const stra: string = i > 0 ? a.slice(i - 14 > 0 ? i - 14 : 0, i) : '';// a[i]
const strb: string = j > 0 ? b.slice(j - 14 > 0 ? j - 14 : 0, j) : '';// b[j]
const sum: string = String(Number(stra) + Number(strb));// 求和
if (sum.length === 15) {
res = (Number(sum.slice(1)) + bit) + res;// 刪掉首位數字
bit = 1;
} else {
res = (Number(sum) + bit) + res;
bit = 0;
}
i -= 14;
j -= 14;
}
return bit === 1 ? 1 + res : res;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/251690.html
標籤:其他
