I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum o

#include<iostream>
#include<string>
using namespace std;
int main(void)
{
string add(string str1, string str2);
int n, i, j;
cin>>n;
string str1, str2, tstr1, tstr2;
for(i = 1; i <= n; i++)
{
cout<<"Case "<<i<<":\n";
cin>>str1>>str2;
tstr1 = str1;
tstr2 = str2;
int len1 = str1.length();
int len2 = str2.length();
if(len1 > len2)
{
for(j = 0; j < len1 - len2; j++)
{
str2 = "0" + str2;
}
}
else if(len1 < len2)
{
for(j = 0; j < len2 - len1; j++)
{
str1 = "0" + str1;
}
}
cout<<tstr1<<" + "<<tstr2<<" = "<<add(str1, str2)<<endl;
if(i != n) cout<<endl;
}
return 0;
}
string add(string str1, string str2)//字符串做算术加法的函数
{
bool flag = false;
string result = "";
int i;
for(i = str1.length() - 1; i >= 0; i--)
{
int a = str1[i] - '0';
int b = str2[i] - '0';
int sum = 0;
if(flag) sum = 1;
sum += (a + b);
if(sum / 10 > 0) flag = true;
else flag = false;
result = char(sum % 10 + 48) + result;
}
if(flag)
result = '1'+result;//如果有进位就在前面加上1
return result;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值