大数相乘-JavaScript

var multiply = function(num1, num2) {
    const left = '0'.charCodeAt(0);
    // console.log("left:"+left);
    // 首先将字符串用 charCodeAt 转换成对应的数字。
    // num1Arr 取较短的数字, num2Arr 取较长的数字,用 num1Arr 去分别乘 num2Arr 速度会提升15ms
    // 这个是规定一定的方向
    const num1Arr = (num1.length > num2.length ? num2 : num1).split('').map(item => item.charCodeAt(0) - left);
    const num2Arr = (num1.length > num2.length ? num1 : num2).split('').map(item => item.charCodeAt(0) - left);
    let res = [];
    console.log("num1Arr:"+num1Arr);
    console.log("num2Arr:"+num2Arr);
    for (let i = num1Arr.length - 1; i > -1; i--) {
        for (let j = num2Arr.length - 1; j > -1; j--) {
            // 数字的相乘的结果转换为数组,并且 reverse,方便计算
            const resArr = (num1Arr[i] + num2Arr[j]).toString().split('');
            console.log("resArrr:"+resArr+" typeof resArr:"+typeof(resArr));
            resArr.reverse();
            const index = num2Arr.length - 1 - j + num1Arr.length - 1 - i;
            let next = 0, k = 0;
            console.log("----------");
            
            console.log("index:"+index);
            console.log("resArr of length:" +resArr.length);
            while (k < resArr.length || next !== 0) {
                // 结果当前位数加上前一位的进位
                console.log("k: "+k)
                let sum = (res[index + k] | 0) + next;//清零,再获取。
                console.log("test"+resArr[index+k] | 0)
                console.log("sum1: "+sum);
                // 若 k < resArr,即非最后一位进位
                if (k < resArr.length) {
                    sum += +resArr[k];
                    console.log("sum2: "+sum);
                }
                res[index + k] = sum % 10;
                // 若 sum 大于10,进位 = 1
                next = sum / 10 >= 1 ? 1: 0;
                console.log("test :"+resArr[index+k])
                console.log("next: "+next);
                k++;
            }
            console.log("***res"+res)
            console.log("resArrr1:"+resArr+" typeof resArr1:"+typeof(resArr));
        }
    }
    console.log("-------res:"+res)
    // 去除结果前的 0
    while (res.length > 1 && res[res.length - 1] === 0) {
        res.pop();
    }
    return res.reverse().join('');
};

console.log(multiply("999","3333"));

实现结果:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flower in my heart

你的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值