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

猜你喜欢

转载自blog.csdn.net/xiaoxiaoyoumeng/article/details/81558897