题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002
题目:
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
Sample Input
2 1 2 112233445566778899 998877665544332211
Sample Output
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
解题思路:这个题目我是用字符串来写的,把一串数字看成字符串输入,再把两个字符串反排序,方便从个位开始相加,然后比较
字符串的长度,可以用size也可以用length,但是绝对不可以用compare,compare是用来比较字符串大小的而不是长度,我做题目
时就是就是误用了compare,导致一直WA,比较 完长度后,两个字符串相加, 再把结果赋值给用长度长的字符串,详情请看代
码。
代码如下:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int n,i,m,k=0;
string str,str1,str2,str3;
while(cin>>n)
{
while(n--)
{
k++;
cin>>str>>str1;
str2=str;str3=str1;
reverse(str.begin(),str.end());//反排序
reverse(str1.begin(),str1.end());
if(str.size()<str1.size())
{
swap(str,str1);//str,str1交换位置
}
for(i=0;i<str1.length();i++)//i要小于字符串长度小的字符串
{
m=(str[i]-'0')+(str1[i]-'0');//使字符变为数字相加
if(m>9)
{
str[i]=m%10+'0';
str[i+1]+=1;//满10进1
}
else {str[i]=m+'0';}
}
reverse(str.begin(),str.end());
cout<<"Case "<<k<<":"<<endl;
cout<<str2<<" + "<<str3<<" = "<<str<<endl;
if(n>0) cout<<endl;
}
}
return 0;
}