zoukankan      html  css  js  c++  java
  • js大数相加和大数相乘

    1. 大数相加

    function addBigNum(a,b){
        var res = '',
            loc = 0;
        a = a.split('');
        b = b.split('');
        while(a.length || b.length || loc){
            //~~把字符串转换为数字,用~~而不用parseInt,是因为~~可以将undefined转换为0,当a或b数组超限,不用再判断undefined
            //注意这里的+=,每次都加了loc本身,loc为true,相当于加1,loc为false,相当于加0
            loc += ~~a.pop() + ~~b.pop();
            //字符串连接,将个位加到res头部
            res = (loc % 10) + res;
            //当个位数和大于9,产生进位,需要往res头部继续加1,此时loc变为true,true + 任何数字,true会被转换为1
            loc = loc > 9;
        }
        return res.replace(/^0+/,'');
    }

    2. 大数相乘

    function multiplyBigNum(num1, num2) {
        //判断输入是不是数字
        if (isNaN(num1) || isNaN(num2)) return "";
        let len1 = num1.length,
            len2 = num2.length;
        let pos = [];
    
        //j放外面,先固定被乘数的一位,分别去乘乘数的每一位,更符合竖式演算法
        for (let j = len2 - 1; j >= 0; j--) {
            for (let i = len1 - 1; i >= 0; i--) {
                //两个个位数相乘,最多产生两位数,index1代表十位,index2代表个位
                let index1 = i + j,
                    index2 = i + j + 1;
                //两个个位数乘积加上当前位置个位已累积的数字,会产生进位,比如08 + 7 = 15,产生了进位1
                let mul = num1[i] * num2[j] + (pos[index2] || 0);
                //mul包含新计算的十位,加上原有的十位就是最新的十位
                pos[index1] = Math.floor(mul / 10) + (pos[index1] || 0);
                //mul的个位就是最新的个位
                pos[index2] = mul % 10;
            }
        }
    
        //去掉前置0
        let result = pos.join("").replace(/^0+/, "");
    
        return result || '0';
    }
    参考: https://segmentfault.com/a/1190000015979292?utm_source=tag-newest

  • 相关阅读:
    selenium+phantomjs爬取bilibili
    使用 python 开发 Web Service
    OBIEE 立方刷新的问题
    解析OracleOLAP使用MView刷新Cube
    Codeforces Round #755 (Div. 2, based on Technocup 2022 Elimination Round 2)(CF1589)题解
    Codeforces Round #754 (Div. 2)(CF1605)题解
    完美解读Linux中文件系统的目录结构
    C#中获取程序当前路径的集中方法
    30个优秀.net在线学习资源站点
    如何删除windows service(转帖)
  • 原文地址:https://www.cnblogs.com/mengff/p/12859381.html
Copyright © 2011-2022 走看看