#include <iostream>
#include<deque>
#include<string>
using namespace std;
string add(string a, string b) //此函数默认a的长度大于b(可以在main函数里用if语句控制a的长度大于b)
{
deque<int>sum; //sum用来存储和的每一位
int carry = 0; //carry表示进位
int i = a.length()-1;
int j = b.length()-1;
for(; i >= 0,j >= 0; --i,--j)
{
int wei_sum = (a[i] - '0') + (b[j] - '0') + carry; //wei_sum表示a,b每个对应相同的位相加的和
if(wei_sum >= 10)
{
carry = 1;
sum.push_front(wei_sum-10);
}
else
{
carry = 0;
sum.push_front(wei_sum);
}
}
for(int k = a.length()-b.length()-1; k >= 0; --k) //算a比b长的那部分的和
{
int wei_sum = (a[k] - '0') + carry; //此处一定要加上之前的进位值!因为之前的carry有可能为1.
if(wei_sum >= 10)
{
carry = 1;
sum.push_front(wei_sum-10);
}
else
{
carry = 0;
sum.push_front(wei_sum);
}
}
if(carry == 1)
sum.push_front(1);
string Sum;
for(auto d: sum)
Sum = Sum + char(d + '0'); //把sum转化为string
return Sum;
}
int main()
{
string a,b;
cin >> a >> b;
if(a.length() > b.length())
cout << a << " + " << b << " = " << add(a,b);
else
cout << a << " + " << b << " = " << add(b,a);
return 0;
}
大数加法(通用型)
最新推荐文章于 2023-01-14 23:22:16 发布