HDU 1002 A + B Problem II(大数加法,C,Java两个版本)



A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 300365    Accepted Submission(s): 57917


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 = 1111111111111111110
 

Author

Ignatius.L

原题链接 :http://acm.hdu.edu.cn/showproblem.php?pid=1002

大数加法,不解释!

AC代码

#include <cstdio>
#include <cstring>
#define maxn 1005
int main()
{
    int n;
    int da[maxn],db[maxn],c[maxn];
    char a1[maxn],a2[maxn];
    scanf("%d",&n);
    for(int kase=1; kase<=n; kase++)
    {
        scanf("%s",a1);
        scanf("%s",a2);
        printf("Case %d:\n",kase);
        printf("%s + %s = ",a1,a2);
        int len1=strlen(a1);
        int len2=strlen(a2);
        memset(da,0,sizeof(da));
        memset(db,0,sizeof(db));
        memset(c,0,sizeof(c));
        int len=len1>len2?len1:len2;
        int k=0;
        for(int i=len1-1; i>=0; i--)
            da[k++]=a1[i]-'0';
        k=0;
        for(int i=len2-1; i>=0; i--)
            db[k++]=a2[i]-'0';
        int carry=0;
        for(int i=0; i<len; i++)
        {
            c[i]=(da[i]+db[i]+carry)%10;
            carry=(da[i]+db[i]+carry)/10;
        }
        bool start=false;//此变量用于跳过多余的0
        for(int i=len; i>=0; i--)
        {
            if(start)
                printf("%d",c[i]);//如果跳过多余的0,则输出
            else if(c[i])
            {
                printf("%d",c[i]);
                start=true;//遇到第一个非0值,则跳过多余的0
            }
        }
        printf("\n");
        if(kase!=n)
            printf("\n");
    }
}<span style="font-size:18px;color:#3333ff;">
</span>

Java大数

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n =sc.nextInt();
		for(int i=1;i<=n;i++){
			BigInteger a = sc.nextBigInteger();
			BigInteger b = sc.nextBigInteger();
			System.out.println("Case "+i+":");
			System.out.println(a+" + "+b+" = "+a.add(b));
			if(i!=n){
				System.out.println();
			}
		}
	}
}


你可能感兴趣的:(HDU1002)