杭電ACM—HDU 1002 A + B Problem II
阿新 • • 發佈:2019-01-25
題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1002
題目:
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; }