以前用C的char数组做的,今天用C++的string写了一遍。
代码:
1 #include <string>
2 #include <iostream>
3 using namespace std;
4
5 string add(string s1,string s2);
6 int carry;
7
8 int main()
9 {
10 string a,b;
11 int T,i,j,k=1;
12 cin>>T;
13 do
14 {
15 cin>>a>>b;
16 cout<<"Case "<<k++<<":"<<endl;
17 cout<<a<<" + "<<b<<" = "<<add(a,b)<<endl;
18 }while(--T);
19
20 //system("pause");
21 return 0;
22 }
23
24 string add(string s1,string s2)
25 {
26 string s;
27 string::size_type i,j;
28 int t,carry,len1,len2;
29
30 if(s1.length() < s2.length())
31 {
32 s = s1;
33 s1 = s2;
34 s2 = s;
35 }
36 len1 = s1.length();
37 len2 = s2.length();
38
39 carry = 0;
40 for(i = len1-1 ,j = len2-1; j != string::npos ; --i,--j)
41 {
42 t =s1[i]-'0' + s2[j]-'0'+carry;
43 s1[i] ='0' + t%10;
44 carry = t/10;
45 }
46
47 if(carry)
48 for(j = i ; j != string::npos; --j)
49 {
50 t = s1[j]-'0'+carry;
51 s1[j] = '0' +t%10;
52 carry = t/10;
53 }
54 if(carry) s1.insert(0,1,'1');
55 return s1;
56 }