现在的位置: 首页 > 综合 > 正文

大数运算——HDOJ 1002

2013年10月23日 ⁄ 综合 ⁄ 共 740字 ⁄ 字号 评论关闭

HDOJ 1002 A+B

/*
HDOJ 1002
大数加法
*/

#include <iostream>
#include <string>
using namespace std;

int a[1001],b[1001],sum[1001];

int main()
{
	int nCase,i,j,cf,temp,
		length_a,length_b,length_sum;
	string temp_a,temp_b;
	
	cin>>nCase;
	for(i=0;i<nCase;i++)
	{
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		memset(sum,0,sizeof(sum));

		cin>>temp_a>>temp_b;
		
		length_a=temp_a.length();
		length_b=temp_b.length();
		
		for(j=0;j<length_a;j++)
			a[j]=temp_a[length_a-j-1]-'0';
		for(j=0;j<length_b;j++)
			b[j]=temp_b[length_b-j-1]-'0';
		
		length_sum=length_a>length_b?length_a:length_b;
		
		cf=0; //进位
		for(j=0;j<length_sum;j++)	
		{
			temp=a[j]+b[j]+cf;
			sum[j]=temp%10;
			cf=temp/10;
		}
		
		cout<<"Case "<<i+1<<":"<<endl;
		cout<<temp_a<<" + "<<temp_b<<" = ";
		for(j=length_sum-1;j>=0;j--)
			cout<<sum[j];
		cout<<endl;
		if(i != nCase-1)
			cout<<endl;
	}
	return 0;
}

抱歉!评论已关闭.