码迷,mamicode.com
首页 > 其他好文 > 详细

两个超大的数相减

时间:2020-05-26 01:23:06      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:+=   ===   else   rac   推荐   text   抄袭   ever   ext   

function subtract(f, t) {
    f += ‘‘;
    t += ‘‘;
    let fl = f.length, tl = t.length, minus = false, minuend = f, subtractor = t, len = tl, maxLen = fl, m, s, currIndex, currT = false, i, sp;
    function reverse(s) {
        return s.split(‘‘).reverse();
    }

    if (fl < tl) {
        minus = true;
        minuend = t;
        subtractor = f;
        len = fl;
        maxLen = tl;
    } else if (fl === tl) {
        for (i = 0; i < fl; i++) {
            if (f[i] > t[i]) {
                minus = false;
                minuend = f;
                subtractor = t;
                len = tl;
                maxLen = fl;
                break;
            } else if (f[i] < t[i]) {
                minus = true;
                minuend = t;
                subtractor = f;
                len = fl;
                maxLen = tl;
                break;
            }
        }
    }
    minuend = reverse(minuend);
    subtractor = reverse(subtractor);
    for (i = 0; i < len; i++) {
        m = minuend[i] * 1;
        s = subtractor[i] * 1;
        if (m > s) {
            minuend[i] = m - s;
        } else if (m < s) {
            currIndex = i + 1;
            do {
                if (minuend[currIndex] !== ‘0‘) {
                    sp = currIndex - i;
                    minuend[currIndex] = minuend[currIndex] * 1 - 1 + ‘‘;
                    currIndex--;
                    for (let j = 0; j < sp; j++) {
                        if (currIndex === i) {
                            minuend[currIndex] = 10 + m - s + ‘‘;
                        } else {
                            minuend[currIndex--] = ‘9‘;
                        }
                    }
                    currT = false;
                } else {
                    currT = true;
                }
            } while (currT && ++currIndex < maxLen);
        } else {
            minuend[i] = 0;
        }
    }
    minuend = reverse(minuend.join(‘‘).replace(/0+$/gi, ‘‘)).join(‘‘);
    return minus ? ‘-‘ + minuend : minuend;
}

声明:严禁抄袭,欢迎转载!不过请带上博文链接!

或者你有更好的实现方式、或者你觉得有可以优化的地方,不妨评论讨论下!觉得得到帮助的可以点个推荐,让更多人也可以得到帮助。

两个超大的数相减

标签:+=   ===   else   rac   推荐   text   抄袭   ever   ext   

原文地址:https://www.cnblogs.com/wuxiexy/p/12961931.html

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