Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
大整数加法,字符串模拟。
class Solution {
public:
string addStrings(string num1, string num2) {
string num = "0123456789";
int size1 = num1.size();
int size2 = num2.size();
string ans = "";
if( size1 > size2 ) {
for( int i = 0; i < size1 - size2; i++ ) {
num2 = "0" + num2;
}
}
if( size2 > size1 ) {
for( int i = 0; i < size2 - size1; i++ ) {
num1 = "0" + num1;
}
}
int i = size1 > size2 ? size1 - 1 : size2 - 1;
int r = 0;
while( i >= 0 ) {
int add1 = num1[i] - '0';
int add2 = num2[i] - '0';
int add = add1 + add2 + r;
if( add > 9 ) r = 1;
else r = 0;
add = add % 10;
ans = num[add] + ans;
i--;
}
if( r == 1 ) {
ans = "1" + ans;
}
return ans;
}
};