A+B Problem II(高精度运算)

A+B Problem II

时间限制:3000 ms  |  内存限制:65535 KB
难度:3
描述

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

A,B must be positive.

输入
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.
输出
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.
样例输入
2
1 2
112233445566778899 998877665544332211
样例输出
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

c语言实现:

02.#include<iostream> 
03
.#include<cstdio> 04.#include<cstring> 05.#include<cstdlib> 06.#define N 1001 07.using namespace std; 08. 09.char ch1[N],ch2[N]; 10.int num1[N],num2[N]; 11.int main() 12.{ 13. int count,i,j,len1,len2,len,T; 14. scanf("%d",&T); 15. count=0; 16. 17. do 18. { 19. ++count; 20. scanf("%s%s",ch1,ch2); 21. len1=strlen(ch1); 22. len2=strlen(ch2); 23. memset(num1,0,N*sizeof(num1[0])); 24. memset(num2,0,N*sizeof(num2[0])); 25. 26. for(i=len1-1,j=0;i>=0;--i,++j)//从个位开始转化并存放 27. num1[j]=ch1[i]-'0'; 28. 29. for(i=len2-1,j=0;i>=0;--i,++j)//从个位开始转化并存放 30. num2[j]=ch2[i]-'0'; 31. 32. len =len1>len2 ? len1:len2; 33. for(i=0;i<len;++i) 34. { 35. num1[i]+=num2[i]; 36. if(num1[i]>9&&i<len) 37. { 38. num1[i]-=10; 39. num1[i+1]++;//进位 40. } 41. } 42. 43. printf("Case %d:\n",count); 44. printf("%s + %s = ",ch1,ch2); 45. 46. if(num1[len]) printf("%d",num1[len]);//可能存在的进位 47. for(i=len-1 ; i >=0; --i) 48. printf("%d",num1[i]); 49. printf("\n"); 50. }while(--T); 51. 52. // system("pause"); 53. return 0; 54.}

JAVA实现:

02.import java.math.BigInteger;
03.import java.util.Scanner;
04.public class Main{
05.  
06.    public static void main(String args[]) {
07.       Scanner cin=new Scanner(System.in);
08.       int n=cin.nextInt();
09.       BigInteger a,b;
10.       for(int i=1;i<=n;i++){
11.           a=cin.nextBigInteger();
12.           b=cin.nextBigInteger();
13.           System.out.println("Case "+i+":");
14.           System.out.println(a.toString()+" + "+b.toString()+" = "+a.add(b));
15.       }
16.    }
17.}
 
原文地址:https://www.cnblogs.com/hpuwangjunling/p/2374707.html