码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript实现大整数减法

时间:2018-08-13 22:34:04      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:substring   width   height   博文   aic   sni   img   string   模拟   

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

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

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;
}

 

技术分享图片

JavaScript实现大整数减法

标签:substring   width   height   博文   aic   sni   img   string   模拟   

原文地址:https://www.cnblogs.com/zgsxh/p/9471417.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!