两个超大的数相减
Posted wuxie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两个超大的数相减相关的知识,希望对你有一定的参考价值。
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; }
声明:严禁抄袭,欢迎转载!不过请带上博文链接!
或者你有更好的实现方式、或者你觉得有可以优化的地方,不妨评论讨论下!觉得得到帮助的可以点个推荐,让更多人也可以得到帮助。
以上是关于两个超大的数相减的主要内容,如果未能解决你的问题,请参考以下文章
SqlServer数据库要求按照两数相减结果的绝对值正序排列怎么写sql语句?