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