您的位置:首页 > 其它

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

2017-06-28 10:13 633 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐