zoukankan      html  css  js  c++  java
  • JavaScript实现大整数减法

    继上一篇博文写了大整数加法之后,我又模拟上篇博文的算法,自己实现了大整数减法。

    大整数减法相对于加法来说,稍微复杂一点。由于要考虑一些情况:

    1. 两个数相减,可能会出现结果为正、负和0三种情况;

    2. 会出现借位的情况,而且还要考虑最高位时有没有借位。

    实现代码如下:

    function subString(a,b) {
        //将字符串a和b补全成同等长度
        while (a.length < b.length){
            a = '0' + a;
        }
        while (b.length < a.length){
            b = '0' + b;
        }
        //res保存结果,c用来标识有无借位的情况
        var res='', c=0;
        a = a.split('');
        b = b.split('');
        while (a.length) {
            var num1 = ~~a.pop();
            var num2 = ~~b.pop();
            if (num1 >= num2){
                c = num1 - num2 - c;
                res = c + res;
                c = false;
            }else {
                c = num1 + 10 - num2 - c;
                res = c + res;
                c = true
            }
            //判断最高位有无借位,若有借位,则说明结果为负数
            if (a.length === 0 && c){
                res = '-' + res
            }
    
        }
        res = res.replace(/^0+/,'');
        //判断最后的结果是否为0
        if (res === ''){
            res = 0;
        }
        return res;
    }
  • 相关阅读:
    众皓网络(T 面试)
    骑芯供应链(T 面试)
    骑芯供应链(W 笔试)
    面试问题_一拉到底
    Java后端学习路线_备战
    docker 容器
    技术展望
    索引 命令
    索引 概念原理
    面试技能更新
  • 原文地址:https://www.cnblogs.com/zgsxh/p/9471417.html
Copyright © 2011-2022 走看看