HDU1002 A + B Problem II
需要注意的点:
1.输入数字的开头0要删除
2.最后的进位
3.最后一个输出没有空行
1 #include <iostream> 2 #include <stack> 3 #include <string> 4 #include <cstring> 5 using namespace std; 6 int main(){ 7 //freopen("in.txt","r",stdin); 8 int T; 9 cin>>T; 10 string s1,s2; 11 int num = 0; 12 while(T--){ 13 cin>>s1>>s2; 14 s1.erase(0,s1.find_first_not_of("0")); 15 s2.erase(0,s2.find_first_not_of("0")); 16 if(s1.size()==0) s1="0";//如果输入为"000",变成"0" 17 if(s2.size()==0) s2="0"; 18 cout<<"Case "<<++num<<":"<<endl; 19 cout<<s1<<" + "<<s2<<" = "; 20 int i = s1.length()-1,j = s2.length()-1; 21 stack<int> result; 22 int flag = 0; 23 while(i>=0&&j>=0){ 24 int a = s1[i--]-'0'; 25 int b = s2[j--]-'0'; 26 int c; 27 c = a+b+flag; 28 if(c>=10){ 29 c = c - 10; 30 flag = 1; 31 } 32 else{ 33 flag = 0; 34 } 35 result.push(c); 36 } 37 while(i>=0){ 38 int p = s1[i--]-'0'; 39 int q = p+flag; 40 if(q>=10){ 41 flag = 1; 42 q = q -10; 43 }else{ 44 flag = 0; 45 } 46 result.push(q); 47 } 48 while(j>=0){ 49 int p = s2[j--]-'0'; 50 int q = p+flag; 51 if(q>=10){ 52 flag = 1; 53 q = q -10; 54 }else{ 55 flag = 0; 56 } 57 result.push(q); 58 } 59 if(flag==1){//最后的进位 60 result.push(1); 61 } 62 while(!result.empty()){ 63 cout<<result.top();//输出结果 64 result.pop(); 65 } 66 cout<<endl; 67 if(T)cout<<endl;//最后一行没有换行 68 } 69 return 0; 70 }