#include<algorithm>
#include<string>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;
int main()
{
int temp = 0;
string a, b;
cin >> a >> b;
a = a.substr(a.find_first_not_of("0"));
b = b.substr(b.find_first_not_of("0"));
long long lenA = a.length();
long long lenB = b.length();
long long len = max(lenA,lenB) + 10;
string answer(len,'0');
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
//把a拷贝到answer中
for (int i = 0; i < lenA; i++)
{
answer.at(i) = a.at(i);//把字符串a复制给字符串answer
}
for (int i = 0; i < lenB; i++)//开始a+b
{
temp += (answer.at(i) - '0') + (b.at(i) - '0');
answer.at(i) = temp % 10 + '0';
temp = temp / 10;
}
if (temp == 1)//这里很特殊 我们要考虑是否temp==1(就是是否进位)
{
answer.at(lenB) += 1;
}
reverse(answer.begin(), answer.end());
answer = answer.substr(answer.find_first_not_of("0"));
cout << answer;
return 0;
}
少年,让我们好好的去理解这个代码的整个过程吧
a.substr(a.find_first_not_of(“0”));//这行代码的意思是我们要将字符串中前面的’0‘给去掉 。 列入a的字符串是“000000123456789”,通过这段代码,我可以将a这个字符串变成“123456789” 说白了就是防止非法数据。为何要这里说呢,就是为了让你们更好的理解
answer = answer.substr(answer.find_first_not_of(“0”));这段代码
reverse();这个函数的作用是为了将字符串的顺序个反过来。
例子:
string c(“12345”);
reverse(c.begin(),c.end());
cout<<c;
这个时候的c是等于“45321”;