Home > Web Front-end > JS Tutorial > body text

Problems with adding big data in JavaScript_javascript skills

WBOY
Release: 2016-05-16 18:04:03
Original
1261 people have browsed it

It’s also an interview question, from an interview with Youdao Front End.
Write a function to handle the addition of big data. The so-called big data refers to data that exceeds the representation range of conventional data types such as integers and long integers. The implementation language is not limited.
I implemented it using js. Let me talk about my own ideas:
1. First of all, the most important part of this question is how to store big data? What data type should be used to save it? The simplest and feasible way is String
2. After determining what type to use to save the data, the problem becomes clear. First, determine the length of the two incoming strings, take the shortest len ​​loop, add the corresponding bits starting from the low bit, and pay attention to saving the carry. After the short data is processed, the carry is handed over to the remaining part of the longer string for processing.
Look at the code for detailed implementation. For a complete example, see jsfiddle

Copy the code The code is as follows:

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('');
};

and above.
PS: Actually, I adapted this interview question. The examiner of the original interview question reminded me to use strings to save big data. This actually reduces the difficulty~~
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!