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 }
     
  • 相关阅读:
    冲刺第一天
    Nacos微服务体系配置管理
    Nacos配置中心客户端程序
    Nacos配置中心最佳实践
    SpringCloud2020整合Nacos-Bootstrap配置不生效的解决
    18.SpringCloud Alibaba Nacos服务注册和配置中心
    17、SpringCloud Alibaba入门简介
    SpringBoot热部署
    SpringBoot请求处理-常用参数注解使用
    5、创建springcloud alibaba工程
  • 原文地址:https://www.cnblogs.com/omigia/p/3745917.html
Copyright © 2011-2022 走看看