JavaScript Big Data Addition

Source: Internet
Author: User

This is also an interview question from youdao frontend.
Write a function to deal with the problem of adding big data. The so-called big data refers to the data that exceeds the range of general data types such as integer and long integer. The implementation language is not limited.
I implemented it using js. Let's talk about my own ideas:
1. First, how to store big data is the most important part of this question? What data type is used for storage? The simplest and most feasible method is String.
2. After determining the type of data to be stored, this question becomes clear. First, judge the length of the two input strings, and take the shortest len loop. The two correspond to the bits from the low position and save the carry. After the short data processing is complete, the bitwise is handed over to the rest of the long string for processing.
For more information about the implementation, see jsfiddle. Copy codeCode: 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 ('');

PS: Actually, I adapted this interview question. The original interview question examiner prompted me to store big data using strings, which actually reduced the difficulty ~~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.