七牛云笔试的一道大数乘法题,两个大数相乘还是有问题。。。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>BigInteger</title>
</head>
<body>
<script>
function NewBigInt(n) {
this.array = [];
var mod;
while(parseInt(n, 10)) {
mod = n % 10;
n /= 10;
n = parseInt(n, 10);
this.array.unshift(mod);
}
return this.array.join('');
}
function BigInt_Mul(a, b) {
var arrA = bigInt.split('');
var arrB = bigInt2.split('');
var lenA = arrA.length;
var lenB = arrB.length;
var res = [], resLen;
var i, j, k, tempArr = [], tempArrLen = 0, jinwei = 0, temp, gewei;
for(j = lenB-1; j >= 0; j--) {
gewei = 0, jinwei = 0;
tempArr = [];
for(i = lenA-1; i >= 0; i--) {
temp = parseInt(arrB[j], 10) * parseInt(arrA[i], 10);
gewei = temp % 10;
tempArr.unshift((gewei = jinwei ? gewei+jinwei : gewei));
jinwei = parseInt((temp / 10), 10);
}
if(jinwei) {
tempArr.unshift(jinwei);
}
console.log(tempArr);
tempArrLen = tempArr.length;
gewei = 0, jinwei = 0;
for(resLen = res.length, k = resLen-1; k >= 0; k--) {
if(res[k] === undefined) {
res.splice(k, 0, tempArr.slice(0, tempArrLen-(resLen-k-1)));
break;
} else {
temp = parseInt(res[k], 10) * parseInt(tempArr[tempArrLen-1 - (lenA-i)], 10);
gewei = temp % 10;
res.unshift((gewei = jinwei ? gewei+jinwei : gewei));
jinwei = parseInt((temp / 10), 10);
}
}
}
console.log(res);
return res.join('');
}
var bigInt = NewBigInt(52);
var bigInt2 = NewBigInt(12);
console.log(bigInt);
console.log(bigInt2);
console.log(BigInt_Mul(bigInt, bigInt2));
</script>
</body>
</html>