HDU - 1002 A + B Problem II 详细题解

xiaoxiao2021-02-28  109

A + B Problem II

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 详细题解: 很明显,这道题是一道大数相加的题目,所以我们不能用 int ; long int ; long long int ;进行求解。偷偷告诉你,题中有句话告诉你“你可以假设每个数字的长度都不超过 1000”,这个提示是不是让我们一下子想到我们可以利用字符串进行求解呢。 首先我们需要定义两个字符数组来储存这两个大大的数字,A[],B[],并求出这两个数字的长度。当然,由于我们使用字符数组进行储存的,所以进行相加这个功能还需 要我们把字符数组转化为int型数组。那么这个数组开多大合适呢?我们想一想,两个数字相加是不是从最小位个位开始呢,最终求得的结果的长度或者与两个数字中较长的 那个相等或者比两个数字中较长的那个多1。如此一来,只要知道两个数字中哪一个数字较长我们就可以知道转化后的数组开多大了,a[max],b[max],c[max+1](用来储存结 果)。 然后从小位开始将两个数字依次进行相加,当当前数字和大于9时,当前位数字需要减去10,较高以为数字加1。 最后,将结果按照题示要求输出就好了。 下面附上AC代码: #include<stdio.h> #include<string.h> #include<iostream> using namespace std; int main(){ int t,i,k; while(cin>>t){ for(i=0;i<t;i++){ char A[1005],B[1005]; cin>>A>>B; int strlenA=strlen(A); int strlenB=strlen(B); cout<<"Case"<<" "<<i+1<<":"<<endl; for(k=0;k<strlenA;k++) cout<<A[k]; cout<<" "<<"+"<<" "; for(k=0;k<strlenB;k++) cout<<B[k]; cout<<" "<<"="<<" "; int max=strlenA>strlenB?strlenA:strlenB; int a[max]; int b[max]; int c[max+1]; for(k=max+1;k>0;k--){ c[k-1]=0; } for(k=max;k>0;k--){ if(strlenA>0) a[k-1]=A[strlenA-1]-'0'; else a[k-1]=0; if(strlenB>0) b[k-1]=B[strlenB-1]-'0'; else b[k-1]=0; strlenA--; strlenB--; } for(k=max+1;k>1;k--){ c[k-1]+=(a[k-2]+b[k-2]); if(c[k-1]>9){ c[k-1]-=10; c[k-2]++; } } if(c[0]!=0) cout<<c[0]; for(k=1;k<max+1;k++) cout<<c[k]; cout<<endl; if((i+1)!=t) cout<<endl; } } }
转载请注明原文地址: https://www.6miu.com/read-29513.html

最新回复(0)