LeetCode/solutions/415. Add Strings.md

31 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [415. Add Strings](https://leetcode.com/problems/add-strings/description/)
# 思路
题目要求计算两个大数的和。
可以先定义一位的加法digit_add然后再从后往前遍历num1和num2并不断调用digit_add即可完成大数相加。
# C++
```
class Solution {
private:
int digit_add(const int d1, const int d2, int &cin){
int sum = d1 + d2 + cin;
cin = sum / 10;
return sum % 10;
}
public:
string addStrings(string num1, string num2){
vector<char>res;
int cin = 0;
int i1 = num1.size() - 1, i2 = num2.size() - 1;
while(i1 >= 0 && i2 >= 0){
res.push_back('0' + digit_add(num1[i1--] - '0', num2[i2--] - '0', cin));
}
// 以下两个循环至多执行一个
while(i1 >= 0) res.push_back('0' + digit_add(num1[i1--] - '0', 0, cin));
while(i2 >= 0) res.push_back('0' + digit_add(num2[i2--] - '0', 0, cin));
if(cin != 0) res.push_back(cin + '0');
reverse(res.begin(), res.end());
return string(res.begin(), res.end());
}
};
```