zoukankan      html  css  js  c++  java
  • 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
     
    难点是,数据类型最长有32位(4字节或者2字),数值范围是-2147483648~2147483648或者0~4294967295,但题目中指出输入数据位数长度可以达到1000位,10^999>>4294967295,故不能用常规方法
     
    具体解决方法是,将数字利用字符串的形式表示,每个字符都是数字,1000个连续字符也没问题,再将两个不同字符串相加得到最终结果。
     
    有一次提交时,出现了“Presentation Error”的错误,缘由是输出结果的格式不符合要求,比方少个空格什么的。
     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 int main()
     5 {
     6     int n;
     7     while(cin>>n)//n为case数 
     8  {
     9     for(int i=1;i<=n;i++)
    10     {
    11         string a,b,c;//3个字符串 
    12         cin>>a>>b;
    13         int la=a.length()-1,lb=b.length()-1,jw=0,ta,tb,tt,f=0;
    14         char tc;
    15         while(la>=0||lb>=0)
    16         {
    17         
    18             if(la<0) ta=0;
    19                 else ta=a[la]-'0';
    20             if(lb<0) tb=0;
    21                 else tb=b[lb]-'0';
    22             tt=jw+ta+tb;//tt为a和b两位相加结果 
    23             jw=tt/10;//jw为进位
    24             tc=tt%10+'0';//tc为赋值给字符串c之前的一个中转
    25             if(tc!='0') f=1;//f为进位标志
    26             c+=tc;
    27             la--;lb--;
    28         }
    29         if(jw>0)
    30         {
    31             f=1;
    32             tc=jw+'0';
    33             c+=tc;
    34         }
    35 
    36         if(i!=1) cout<<endl;
    37         cout<<"Case "<<i<<":"<<endl;
    38         cout<<a<<" + "<<b<<" = ";
    39         if(f==1)
    40         {
    41             for(int j=c.length()-1;j>=0;j--)
    42                 cout<<c[j];
    43             cout<<endl;
    44         }
    45         else  cout<<0<<endl;
    46     }
    47     }
    48     return 0;
    49 }
     
  • 相关阅读:
    帮助应届生、年轻程序员快速成长的12个锦囊<转载>
    曾国藩教您:如何富过三代
    Mvc示例代码调试之二——调试示例讲解
    如何处理婚姻问题
    jQuery对象与dom对象相互转换
    Mvc示例代码调试之一----调试工具及设置(用firebug与vs联合调试)
    Mvc示例之三——用Filter进行简单身份验证
    沟通的艺术
    做bs开发需要学习哪些技术
    我所读过的技术书籍
  • 原文地址:https://www.cnblogs.com/omigia/p/3745917.html
Copyright © 2011-2022 走看看