1.題目
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
兩個字元串代表的數字,求加法的結果。不能使用内置的大整數操作或直接将字元串轉為整數。
2.分析
從低位開始,按位來計算,跟手動算兩個數的加法一樣。注意進位,結果用字元串來存儲結果。
3.代碼
string addStrings(string num1, string num2) {
vector<char> sum;
int i = num1.size() - ;
int j = num2.size() - ;
int carry = ;//進位
for (; i >= || j >= ; --i, --j) {
int x = i < ? : num1[i] - '0';
int y = j < ? : num2[j] - '0';
int tmp = x + y + carry;
sum.push_back(tmp % + '0');
carry = tmp / ;
}
if (carry > )
sum.push_back(carry + '0');
return string(sum.rbegin(), sum.rend());
}