js 大整数加法和乘法

这段代码定义了两个函数,add和mul,用于对输入的数字字符串进行加法和乘法运算。它首先将数字字符串转换为数字数组,然后执行计算,最后将结果数组转换回字符串。在计算过程中,采用了逐位相加和逐位相乘的方法,并处理了进位问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 function Big() {
 2     "use strict";
 3 
 4     // 把 '123' 分散为 [3, 2, 1]
 5     function getDigitList(n) {
 6         return (n + "")
 7             .split("")
 8             .reverse()
 9             .map((d) => +d);
10     }
11 
12     function add(n0, n) {
13         if (typeof n0 != "string" || typeof n != "string") {
14             throw Error("Please enter a string");
15         }
16 
17         n0 = getDigitList(n0);
18         n = getDigitList(n);
19         let max = Math.max(n0.length, n.length),
20             _high = 0,
21             digitList = [];
22         for (let i = 0; i < max; i++) {
23             const [low, high = 0] = getDigitList((n0[i] || 0) + (n[i] || 0) + _high);
24             digitList.push(low);
25             _high = high;
26         }
27         if (_high) {
28             digitList.push(_high);
29         }
30         return digitList.reverse().join("");
31     }
32 
33     function mul(n0, n) {
34         if (typeof n0 != "string" || typeof n != "string") {
35             throw Error("Please enter a string");
36         }
37 
38         n0 = getDigitList(n0);
39         n = getDigitList(n);
40         const D1 = n0.reduce(function (D1, d1, i) {
41             let _high = 0;
42             let D2 = n.reduce(function (D2, d2) {
43                 const [low, high = 0] = getDigitList(d1 * d2 + _high);
44                 D2.push(low);
45                 _high = high;
46                 return D2;
47             }, new Array(i).fill(0));
48             _high && D2.push(_high);
49             return add(D1, D2.reverse().join(""));
50         }, "");
51 
52         return D1;
53     }
54 
55     this.add = add;
56     this.mul = mul;
57 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值