首页 > 代码库 > HDU 1002

HDU 1002

大水题

为了心情好点去写的

结果

思路很明确

过程有点曲折

超大数字的计算用字符串来解决

换成减法也许会难点

 1 #include <iostream> 2 #include <string> 3 using namespace std; 4  5 int main() 6 { 7     int T; 8     cin>>T; 9     int t =T;10 11     while(T--)12     {13         string a,b,c,d;14         cin>>a>>b;15 16         c = a;//之后要输出a,b17         d = b;//先备份18         int la = a.length();19         int lb = b.length();20 21         if(la<lb)//简化问题把长短区分开来22         {23             string c = a;24             a = b;25             b = c;26             la = a.length();27             lb = b.length();28         }29 30         char* result = new char[la+1];31         result[0]= 0;32         int dif = la-lb;33         int index = la;34         int add = 0;35         for(int i = lb-1;i>-1;i--)//一直短的那些每位相加36         {37             if(b.at(i)+a.at(dif+i)+add<=0+9)38             {39                 result[index] = b.at(i)+a.at(dif+i)-0 +add;40                 index--;41                 add = 0;42             }else43             {44                 result[index] = b.at(i)+a.at(dif+i)-0-10 +add;45                 index--;46                 add = 1;47             }48         }49         if(la==lb)//等长时的考虑50         {51             if(a.at(0)+b.at(0)>0+9)52             {53                 result[0]=1;54             }55         }else{56         for(int i = dif-1;i>-1;i--)57         {58             if(a.at(i)+add<=9)59             {60                 result[index] = a.at(i)+add;61                 index--;62                 add =0;63             }else64             {65                 result[index] = a.at(i)+add-10;66                 index--;67                 add = 1;68             }69         }70         }71         cout<<"Case "<<t-T<<":"<<endl;72         cout<<c<<" "<<"+"<<" "<<d<<" = ";73 74         if(result[0]!=0)75         {76             cout<<result[0];77         }78        for(int i =1;i<=la;i++)79        {80            cout<<result[i];81        }82        cout<<endl;83        if(T!=0)84        {85         cout<<endl;86        }87     }88 89 }