首頁 > web前端 > js教程 > 主體

JS實作兩個大數(整數)相乘_javascript技巧

WBOY
發布: 2016-05-16 16:50:55
原創
2148 人瀏覽過

大數,即超出語言所能表示的數字最大範圍的數字,此時的數字只能用字串來表示。那麼要如何實現兩個大數相乘呢?我用JS實作了一下,程式碼如下:

複製程式碼 程式碼如下:
console. log(bigMut("567", "1234")); // 699678
function bigMut(big, common) {
big = "";
common = "";
if (bigbig .length big = [common, common = big][0];
}
big = big.split("").reverse();
var oneMutManyRes = [];
var i = 0,
len = big.length;
for (; i oneMutManyRes[oneMutManyRes.length] = oneMutMany(big[i] , common) getLenZero(i);
}
var result = oneMutManyRes[0];
for (i = 1, len = oneMutManyRes.length; i }
return result;
}
function getLenZero(len) {
len = 1;
var. 🎜>ary.length = len;
return ary.join("0");
}
function oneMutMany(one, many) {
one = "";
many = " ";
if (one.length != 1) {
one = [many, many = one][0];
}
one = parseInt(one, 10);
var i = 0,
len = many.length,
resAry = [],
addTo = 0,
curItem,
curRes,
toSave; .split("").reverse();
for (; i curItem = parseInt(many[i] || 0, 10);
curRes = curItem * one addTo;
toSave = curRes % 10;
addTo = (curRes - curRes % 10) / 10;
resAry.unshift(toSave);
}
resAry.unshift(toSave);
}
(ifAry.Aryf]if == 0) {
resAry.splice(0, 1);
}
return resAry.join("");
}
function bigNumAdd(big, common) {
big = "";
common = "";
var maxLen = Math.max(big.length, common.length),
bAry = big.split("").reverse(),
cAry = common.split("").reverse(),
i = 0,
addToNext = 0,
resAry = [],
fn,
sn,
sum;
for (; i fn = parseInt(bAry[i] || 0);
sn = parseInt(cAry[i] || 0);
sum = fn sn addToNext;
addToNext = (sum - sum % 10) / 10;
resAry.unshift(sum % 10);
}
if (resAry[0] =if (resAry[0] = = 0) {
resAry.splice(0, 1);
}
return resAry.join("");
}

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板