hdu_1013_A + B Problem II_(模拟)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002
解题思路:利用数组进行大数的相加。内置数据类型不能满足整数位数的要求。
样例:
<span style="white-space:pre">	</span>1 999
<span style="white-space:pre">	</span>999 1
#include <iostream>
#include <cstring>
using namespace std;
int num1[1010],num2[1010];
int t[1010];
int result[1010];
char str1[1010],str2[1010];

void add(int len1,int len2)
{
	int i,j;
	//字符转换成数字,再反转 
	for(i = 0;i < len1;i++)
		t[i] = str1[i] - 48;
	for(i = len1 - 1,j = 0;i >= 0;i--,j++)
		num1[j] = t[i];
		
	for(i = 0;i < len2;i++)
		t[i] = str2[i] - 48;
	for(i = len2 - 1,j = 0;i >= 0;i--,j++)
		num2[j] = t[i];
	
	int k = 0,temp,cnt = 0;
	i = 0;
	while(i < len1 || i < len2)
	{
		temp = num1[i] + num2[i] + cnt;//cnt表示进位 
		if(temp >= 10)
		{
			cnt = 1;
			result[i] = temp % 10;
		}
		else
		{
			result[k] = temp;
			cnt = 0;
		}
		i++;
		k++;
	}
	result[k] = cnt;//假如是99+99,则最后的进位1要记录下来 
	
	for(i = 0;i < len1;i++)
		cout << str1[i];
	cout << " + ";
	for(i = 0;i < len2;i++)
		cout << str2[i];
	cout << " = ";	
		
	if(result[k] != 0)
	   	   cout << result[k];
	int ii;
	for(ii = k-1;ii >= 0;ii--)
	{
	   	cout << result[ii];
	}
	cout << endl;
}
int main(int argc, char *argv[])
{
	int s,cnt = 1;
	cin >> s;   
	int a = s;      
	while(s--)
	{
		memset(num1,0,sizeof(num1));
		memset(num2,0,sizeof(num2));//每次都要初始化num1和num2 的数组,没有则会WA 
		memset(result,0,sizeof(result));
		cin >> str1 >> str2;
		cout << "Case " << cnt << ":" << endl;
		add(strlen(str1),strlen(str2));
		if(cnt < a) //最后的样例没有空行 
			cout << endl;
		cnt++;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值