题解 | 大数加法
大数加法
https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
class Solution {
public:
string solve(string s, string t) {
int n1 = s.size();
int n2 = t.size();
if(n1<n2)
s = std::string(n2-n1, '0') + s;
else if(n1>n2)
t = std::string(n1-n2, '0') + t;
int jinwei = 0;
int n = max(n1, n2);
int curr = 0;
string res = "";
for(int i=n-1; i>=0; i--){
curr = s[i]-'0' + t[i]-'0' + jinwei;
jinwei = curr / 10;
curr %= 10;
res = char(curr+'0') + res;
}
if(jinwei)
res = char(jinwei+'0') + res;
return res;
}
};
为了能够更简单地相加,首先可以对齐二者长度,短的那个前面补‘0’即可。

