#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string add(string a, string b)//数字长度短的永远在a里存储
{
string sum;
reverse(a.begin(), a.end());//先将两个字符串反转
reverse(b.begin(), b.end());
int size = 0, index = 0, carry = 0, temp = 0;
size = a.size();
if (a.size() > b.size())
{
size = b.size();
swap(a, b);
}
for (int i = 0; i < size; i++)
{
if (carry == 0)
sum = sum + "0";
temp = (a[i] - '0') + (b[i] - '0') + (sum[sum.size() - 1] - '0');//计算这一位的值
sum[sum.size() - 1] = (temp >= 10) ? (temp - 10 + '0') : (temp + '0');// (temp % 10) + '0';//保留个位
carry = (temp >= 10) ? 1 : 0;
if (carry == 1)
sum = sum + "1";
}
for (int i = size; i < b.size(); i++)
{
if (carry == 0)
sum = sum + "0";
temp =(b[i] - '0') + (sum[sum.size() - 1] - '0');//计算这一位的值
sum[sum.size() - 1] = (temp >= 10) ? (temp - 10+'0') : (temp+'0');// (temp % 10) + '0';//保留个位
carry = (temp >= 10) ? 1 : 0;
if (carry == 1)
sum = sum + "1";
}
reverse(sum.begin(), sum.end());
return sum;
}
int main()
{
string a, b, sum;
int times = 0, index = 0;
scanf("%d", ×);
while (times != 0)
{
index++;
cin >> a >> b;
printf("Case %d:\n", index);
printf("%s + %s = %s\n", &a[0], &b[0], &add(a, b)[0]);
times--;
if (times!=0)
printf("\n");
}
return 0;
}
不解释了,自己看吧。
杭电OJ---1002
最新推荐文章于 2021-05-21 07:31:15 发布