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

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;
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值