杭电oj 1002 A + B Problem II

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 = 1111111111111111110


分析

给定T个测试用例(1<=T<=20),每个测试用例都为正数,该正数很大,不超过一千位,意味着我们不能用int、long long int,只能用字符串进行操作。


重点

  1. 格式一定要用题目要求的格式,不然即使自己测试的结果是对的,但是格式不对,系统仍然会判错误。
  2. 从char类型过渡到int类型时,要倒序输入,是因为假设字符串输入“123456”时,在字符串中‘6’是最高位,但是在加法计算过程中‘6’是最低位,因此需要转换一下,方便计算。

代码

//2019-7-14 13:45
//by changfengpolang
//big data A+B
#include<stdio.h>
#include<string.h>

int main()
{
	//字符串最后一位为'\0',因此分配1001个空间 
	char a1[1001]={'\0'}, b1[1001]={'\0'}; 
	//sum保存每一位的运算结果,因为最高位可能还会进位,因此分配1001个空间  
	int a2[1000], b2[1000], sum[1001];
	
	int i=1, j, num, k, r, w;
	int len1, len2;
	//输入测试用例个数 
	scanf("%d", &num);
	while(i<=num)
	{
		//初始化 
		for(j=0;j<1000;j++)               
			a2[j]=0;
		for(j=0;j<1000;j++)
			b2[j]=0;
		for(j=0;j<1001;j++)
			sum[j]=0;
			
		scanf("%s", &a1);
		scanf("%s", &b1);
		len1 = strlen(a1);
		len2 = strlen(b1);
		
		//反转
		//或是按照自己的习惯,只要从低位到高位,每一位都对其运算即可 
		r=0;	
		for(j=len1-1;j>=0;j--)               
		{
			a2[r]=a1[j]-48;
			r++;
		}
		r=0;
		for(j=len2-1;j>=0;j--)
		{
			b2[r]=b1[j]-48;
			r++;
		}
		
		//取字符串a1和b1中较长的字符串的个数 
		if(len1<len2)                  
			k=len2;
		else
			k=len1;
		
		//每一位进行加法运算 
		for(j=0;j<k;j++)
		{
			sum[j]=a2[j]+b2[j]+sum[j];
			//进位时的操作 
			if(sum[j]>=10)
			{
				sum[j]=sum[j]-10;
				w = j+1;
				sum[w]++;
			}
		}
		
		//输出结果
		printf("Case %d:\n", i);	
		for(j=0;j<len1;j++)
			printf("%d", a1[j]-48);
		printf(" + ");
		for(j=0;j<len2;j++)
			printf("%d", b1[j]-48);
		printf(" = ");
		
		if(sum[k])
			k++;
			
		for(j=k-1;j>=0;j--)
			printf("%d", sum[j]);
		printf("\n");
		if(i<num)
			printf("\n");
		i++;	
	}
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值