[LeetCode]415. Add Strings
题目描述
思路
水题,遍历字符串,按位相加即可
代码
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string addStrings(string num1, string num2) {
string res;
int temp1, temp2, carry = 0;
for (int i = num1.size() - 1, j = num2.size() - 1; ; --i, --j) {
if (i < 0 && j < 0)
break;
temp1 = 0, temp2 = 0;
if (i >= 0)
temp1 = num1[i] - '0';
if (j >= 0)
temp2 = num2[j] - '0';
int temp_res = (temp1 + temp2 + carry) % 10;
carry = (temp1 + temp2 + carry) / 10;
res = to_string(temp_res) + res;
}
if (carry)
res = to_string(carry) + res;
return res;
}
};
int main() {
Solution s;
cout << s.addStrings("11", "99") << endl;
system("pause");
return 0;
}
300



被折叠的 条评论
为什么被折叠?



