写一个函数处理大数据的相加问题,所谓的大数据是指超出了整型,长整型之类的常规数据类型表示范围的数据。实现语言不限。
昨天在网上看到这道题,感觉很奇怪,难道还有什么算法能比原生的符号运算更快?看到这个链接:http://niutuku.com/tech/javaScript/258837.shtml,我测试了一下,大数据函数就出错,速度也明显不行,请教这道题的思路是什么? (链接源代码有笔误,我修改了下,贴在下面)
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
window.onload = function () {
console.time("strNumAdd")
var strAdd = function (srcA, srcB) {
var i, temp, tempA, tempB, len, lenA, lenB, carry = 0;
var res = [],
arrA = [],
arrB = [],
cloneArr = [];
arrA = (srcA + "").split("");
arrB = (srcB + "").split("");
arrA.reverse();
arrB.reverse();
lenA = arrA.length;
lenB = arrB.length;
len = lenA > lenB ? lenB : lenA;
for (i = 0; i < len; i++) {
tempA = parseInt(arrA[i], 10);
tempB = parseInt(arrB[i], 10);
temp = tempA + tempB + carry;
if (temp > 9) {
res.push(temp - 10);
carry = 1;
} else {
res.push(temp);
carry = 0;
}
}
cloneArr = lenA > lenB ? arrA : arrB;
for (; i < cloneArr.length; i++) {
tempA = parseInt(cloneArr[i], 10);
temp = tempA + carry;
if (temp > 9) {
res.push(temp - 10);
carry = 1;
} else {
res.push(temp);
carry = 0;
}
}
return (res.reverse()).join('');
};
console.log(strAdd(23909080089709873508234, 9834309800089325675433678))
console.timeEnd("strNumAdd")
console.time("normalAdd")
console.log(23909080089709873508234, 9834309800089325675433678)
console.timeEnd("normalAdd")
}
</script>
</head>
<body>
</body>
</html>
A Javascript library for arbitrary-precision decimal and non-decimal arithmetic
https://github.com/MikeMcl/bignumber.js
一个关于大数运算的 javascript 库。
原生 js 浮点数运算:
bignumber 运算: