大整数的加法

1.问题描述

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.

2.程序

#include<stdio.h>
#include<string.h> 
int main(void)
{
	int n;
	while (scanf("%d", &n) != EOF)
	{
		int i, sum, t, b, c, d, e, f, g;
		int z[1000], y[1000], x[1000];
		char a;
		memset(z, 0, sizeof(z));//初始化内存
		memset(y, 0, sizeof(y));
		memset(x, 0, sizeof(x));
		getchar();
		for (int k = 1; k <= n; k++)
		{
			i = 0; int l = 0;
			while (1)
			{
			jump:a = getchar();
				if (a == 32)//空格
				{
					i = 0;
					l = 1;
					goto jump;
				}
				if (a == 10) break;//换行
				if (l == 0)
				{
					z[i] = a - '0';//第一个数
					b = i;
				}
				else
				{
					y[i] = a - '0';//第二个数
					c = i;
				}
				i++;
			}
			if (b>c)
			{
				d = b;//d表示最长的位数的数组下标 
				e = 0;
				g = b - c;
				while (1)//把位数小的数往后移,和位数大的数对齐
				{
					if (c >= 0) y[b--] = y[c--];
					else y[b--] = 0;
					if (b<0) break;
				}
			}
			else
			{
				d = c;
				e = c - b;
				g = 0;
				while (1)
				{
					if (b >= 0) z[c--] = z[b--];
					else z[c--] = 0;
					if (c<0) break;
				}
			}
			printf("Case %d:\n", k);
			for (i = e; i <= d; i++)//打印第一个数
				printf("%d", z[i]);
			printf(" + ");
			for (i = g; i <= d; i++)//打印第二个数
				printf("%d", y[i]);
			printf(" = ");
			int f = 0;
			for (i = d; i >= 0; i--)//计算两个数的和,放入x中
			{
				x[i] = (z[i] + y[i] + f) % 10;
				f = (z[i] + y[i] + f) / 10;
			}
			if (f) printf("1");
			for (i = 0; i <= d; i++)
			{
				printf("%d", x[i]);
			}
			printf("\n");
			if (k != n) printf("\n");
		}
	}
	return 0;
}

3.思路

用数组存储两个大整数,然后在数组中调整整数的位置,使他们末尾对齐,然后对应的位置相加,注意保存进位,最后输出即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NEU_SML

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值