加入收藏 | 设为首页 | 会员中心 | 我要投稿 辽源站长网 (https://www.0437zz.com/)- 云专线、云连接、智能数据、边缘计算、数据安全!
当前位置: 首页 > 大数据 > 正文

【杭电-oj】-1002-A + B Problem II(大数相加)

发布时间:2021-03-01 18:09:54 所属栏目:大数据 来源:网络整理
导读:A + B Problem II Time Limit: 2000/1000 MS (Java/Others)????Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 314006????Accepted Submission(s): 60840 Problem Description I have a very simple problem for you. Given two integers

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)????Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 314006????Accepted Submission(s): 60840


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 = 2222222222222221110
  
  
?

用字符串存比较大的数,然后把数倒着写,因为比较利于计算,此时应注意方法,再判断最高位有没有进位即可。

但是师傅建议我这么写,记下,下道题试试。

初始化:

【杭电-oj】-1002-A + B Problem II(大数相加)


输出:

【杭电-oj】-1002-A + B Problem II(大数相加)


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
	int n,num=0;
	char a[1010],b[1010];			//把数当做字符串用a,b存
	int l1,l2,l3;
	int numa[1010]={0},numb[1010]={0};		 //分别存储a,b准换为数字后的值 
	scanf("%d",&n);
	while(n--)
	{
		memset (numa,sizeof (numa));
		memset (numb,sizeof (numb));
		scanf("%s %s",a,b);
		l1=strlen(a);
		l2=strlen(b);
		l3=max(l1,l2);
		for(int i=0;i<l1;i++)
			numa[l1-i-1]=a[i]-'0';			//为了方便计算,把数倒着存,注意此处的技巧,会常用 
		for(int i=0;i<l2;i++)
			numb[l2-i-1]=b[i]-'0';
		numb[l3]=0;
		for(int i=0;i<l3;i++)
		{
			numb[i]=numa[i]+numb[i];
			if(numb[i]>9)
			{
				numb[i]=numb[i]-10;
				numb[i+1]++;
			}
		}
		num++;
		printf("Case %d:n",num);
		printf("%s + %s = ",b);
		if(numb[l3]==0)			//判断l3(最后一位)是否为零 
		{
			for(int i=l3-1;i>=0;i--)	//倒着相加,倒着输出 
				printf("%d",numb[i]);
			printf("n");
		}
		else
		{
			for(int i=l3;i>=0;i--)
				printf("%d",numb[i]);
			printf("n"); 
		} 
		if(n!=0)
			printf("n");
	}
	return 0;
}

(编辑:辽源站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读