HDOJ 1002

**

A + B Problem II

**
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 549355 Accepted Submission(s): 104809

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

Author
Ignatius.L

解题思路
题目要求1000位数字的运算,显然即使是longlong也无法满足要求。因此使用char字符组进行逐位的运算。自己写的代码一直无法通过,这里的AC代码来自用户houzena

略有改动。添加了代码注释。

AC

#include<stdio.h>
#include<string.h>
void  Bignum_add(char* s1, char* s2, char* s)
{
	int i, j, a, l1, l2, L, t;
	l1 = strlen(s1);
	l2 = strlen(s2);//字符串长度
	s[0] = '0';
	a = 0;
	if (l1 > l2) L = l1;
	else L = l2;//L为两串长度最大值
	s[L + 1] = '\0';//尾部赋值
	for (i = L; l1 > 0 && l2 > 0; i--)//从尾部开始比较
	{
		a = (s1[--l1] - '0') + (s2[--l2] - '0') + a / 10;//注意0与‘0’区别
		s[i] = a % 10 + '0';//数字转字符
	}
	while (l1) {
		a = (s1[--l1] - '0') + a / 10;
		s[i--] = a % 10 + '0';//若l1还有剩余,赋值给s
	}
	while (l2) {
		a = (s2[--l2] - '0') + a / 10;
		s[i--] = a % 10 + '0';//若l2还有剩余,赋值给s
	}
	s[i] = a / 10 + '0';//头部进位
	t = 0;
	while (s[t] == '0' && t < L) t++;//头部‘0’计数
	strcpy(s, s + t);//去头部的‘0’。原理为对头部‘0’数量进行计数,储存为t,利用strcpy进行后移。例如将‘00001’改为‘1’
}

int main()
{
	int T, d = 1;
	char s[1005], s1[1005], s2[1005];//上限改为1005防止溢出
	scanf("%d", &T);//读入
	while (T--)//进行T次循环
	{
		scanf("%s%s", s1, s2);//字符串读入
		Bignum_add(s1, s2, s);//相加
		printf("Case %d:\n", d++);
		printf("%s + %s = %s\n", s1, s2, s);//使用printf进行输出
		if (T != 0) printf("\n");//还有需要输出的内容,换行
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值