大数加法

大数加法_第1张图片

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     int cnt =1;
 8     int n;
 9     cin>>n;
10     while(n--)
11     {
12         string str1,str2;
13         int var[1000]={0},var1[1000]={0},var2[1000]={0};
14         int len1,len2,lenm;
15         cin>>str1>>str2;
16         len1 = str1.size();
17         len2 = str2.size();
18         lenm = len1>len2 ? len1:len2;
19 
20         for(int i=len1-1,j=0;i>=0;i--)
21         {
22             var1[j++] = str1[i]-'0';
23         }
24         for(int i=len2-1,j=0;i>=0;i--)
25         {
26             var2[j++] = str2[i]-'0';
27         }
28         int ca=0;
29         for(int i=0,j=0;i<lenm;i++)
30         {
31             var[j++] = (var1[i]+var2[i]+ca)%10;
32             ca = (var1[i]+var2[i]+ca)/10;
33         }
34         while(ca)
35         {
36             var[lenm++] = ca%10;
37             ca = ca/10;
38         }
39         cout<<"Case "<<cnt++<<":"<<endl;
40         cout<<str1<<" + "<<str2 <<" = ";
41         for(int i=lenm-1;i>=0;i--)
42         {
43             cout<<var[i];
44         }
45         cout<<endl;
46     }
47     return 0;
48 }

 

你可能感兴趣的:(大数加法)