leetcode - 415. 字符串相加
题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/15b1c2848ba64421b77d08c9de5d4ef9.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAem1tX21vaHVh,size_18,color_FFFFFF,t_70,g_se,x_16)
代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> strToInt(string num){
vector<int> res;
int tn;
for(int i = 0; i < num.size(); i++){
tn = num[i] - '0';
res.push_back(tn);
}
reverse(res.begin(), res.end());
return res;
}
string addStrings(string num1, string num2) {
vector<int> n1 = strToInt(num1);
int ns1 = n1.size();
vector<int> n2 = strToInt(num2);
int ns2 = n2.size();
int flag = 0;
int n = 0;
char c;
string str = "";
int i = 0, j = 0;
while(i < ns1 || j < ns2){
if(i == ns1){
n = n2[j++] + flag;
flag = n / 10;
c = n % 10 + '0';
str += c;
}else if(j == ns2){
n = n1[i++] + flag;
flag = n / 10;
c = n % 10 + '0';
str += c;
}else{
n = n1[i++] + n2[j++] + flag;
flag = n / 10;
c = n % 10 + '0';
str += c;
}
}
if(flag){
str += flag + '0';
}
reverse(str.begin(), str.end());
return str;
}
string addStrings1(string num1, string num2) {
int n, n1, n2;
int i = num1.size() - 1, j = num2.size() - 1;
int flag = 0;
char c;
string str;
while(i >= 0 || j >=0 || flag != 0){
n1 = i >= 0 ? num1[i] - '0' : 0;
n2 = j >= 0 ? num2[j] - '0' : 0;
n = n1 + n2 + flag;
flag = n / 10;
c = n % 10 + '0';
str += c;
i--;j--;
}
reverse(str.begin(), str.end());
return str;
}
int main(){
string num1, num2, res;
cin>>num1>>num2;
res = addStrings(num1, num2);
cout<<res;
return 0;
}