加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

题解报告:hdu 1002 A + B Problem II(大数加法)

发布时间:2020-12-14 03:49:48 所属栏目:大数据 来源:网络整理
导读:Problem Description I have a very simple problem for you. Given two integers A and B,your job is to calculate the Sum of A + B. Input The first line of the input contains an integer T(1=T=20) which means the number of test cases. Then T li

Problem Description

I have a very simple problem for you. Given two integers A and B,your job is to calculate the Sum of A + B.

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 = 2222222222222221110
解题思路:大数加法,简单模拟竖式运算或者直接调用java中BigInteger大数类的add()方法即可。
AC之C++代码:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main(){
 4     string a,b,r;int t,tmp;bool flag;
 5     while(cin>>t){
 6         flag=true;
 7         for(int i=1;i<=t;++i){
 8             cin>>a>>b;tmp=0;r="";
 9             if(!flag)cout<<endl;
10             cout<<"Case "<<i<<":n"<<a<<" + "<<b<<" = ";
11             if(a.size()>b.size())swap(a,b);
12             for(int i=a.size()-1,j=b.size()-1;~j;--i,--j){
13                 int now=(i>=0?a[i]-0:0)+b[j]-0+tmp;
14                 tmp=now>9?1:0;now%=10;
15                 r+=0+now;
16             }
17             if(tmp)r+=1;
18             for(int i=r.size()-1;~i;--i)cout<<r[i];
19             cout<<endl;flag=false;
20         }
21     }
22     return 0;
23 }

AC之java代码:

 1 import java.util.Scanner;
 2 import java.math.BigInteger;
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner scan = new Scanner(System.in);
 6         int t=scan.nextInt();
 7         for(int i=1;i<=t;++i){
 8             BigInteger a = scan.nextBigInteger();
 9             BigInteger b = scan.nextBigInteger();
10             System.out.println("Case "+i+":");
11             System.out.println(a+" + "+b+" = "+a.add(b));
12             if(i!=t)System.out.println();
13         }    
14     }
15 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读