大数计算------杭电HDOJ 1002(简单题)
发布时间:2020-12-14 03:40:28 所属栏目:大数据 来源:网络整理
导读: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
Sample Output
普通int定义数据范围:2147483648~2147483648,就算是__int64 也是有限的,那怎么办呢?我们用数组来计算这道题:
代码如下:
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #include<iostream> using namespace std; #define max 10006 char liu[max][max],xp[max][max],a[max][max]; int d[max]; int main() { int i,j,k; int t,f; int len1,len2,len3; int b; cin>>t; getchar(); for(i=0;i<t;i++) { cin>>liu[i]>>xp[i]; //printf("%sn",liu[i]); //printf("%sn",xp[i]); } for(f=0;f<t;f++) { memset(d,max); len1=strlen(liu[f]); len2=strlen(xp[f]); b=0; for(i=len1-1,j=len2-1;i>=0&&j>=0;i--,j--) { d[b+1]=(d[b]+(liu[f][i]-'0')+(xp[f][j]-'0'))/10; d[b]=(d[b]+(liu[f][i]-'0')+(xp[f][j]-'0'))%10; b=b+1; } if(len1<len2) { for(i=len2-len1-1;i>=0;i--) { d[b+1]=(d[b]+(xp[f][i]-'0'))/10; d[b]=(d[b]+(xp[f][i]-'0'))%10; b=b+1; } } else if(len1>len2) { for(i=len1-len2-1;i>=0;i--) { d[b+1]=(d[b]+(liu[f][i]-'0'))/10; d[b]=(d[b]+(liu[f][i]-'0'))%10; b=b+1; } } printf("Case %d:n",f+1); printf("%s + %s = ",liu[f],xp[f]); for(j=max-1;j>=0;j--) { if(d[j]) break; } for(i=j;i>=0;i--) { printf("%d",d[i]); } printf("n"); if(f!=t-1) printf("n"); } return 0; }实在惭愧,当初不会这道题的解法,活生生的错了40次;
能力有限,代码也不懂得优化,大家要是有什么优化的建议,欢迎提出,大家一起学习进步,谢谢;
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |