2013寒假练习 1000:a+b

地址:http://acm.bit.edu.cn/mod/programming/view.php?id=650
喜闻乐见大数题。a、b两大数(可正可负)相加。1Y,就是写得很麻烦。。后面注释都懒得写了。。

#include<iostream>
#include<cstdio>
using namespace std;
short int a[1005],b[1005],c[1005]; //a和b两个大数的值 ,c为答案	
bool mark1,mark2;     //a和b的符号
short int len1,len2;  //a和b的长度
int i;
void output()                                //输出答案数组
{
	for(i=1004;c[i]==0;i--);
	//if(i==-1) printf("0");
	for(;i>=0;i--) printf("%d",c[i]);
	printf("\n"); 
}
int compare()                    //比较A与B大小
{
	if(len1!=len2) return len1>len2;
	for(int i=len1-1;i>=0;i--) 
	{
		if(a[i]!=b[i]) return a[i]>b[i];
	}
	return 2;
}
void change()                    //交换A与B
{
	short temp;
	for(i=999;i>=0;i--)
	{
		temp=a[i],a[i]=b[i],b[i]=temp;
	}
	temp=len1,len1=len2,len2=temp;
}
void plus0()
{
	short jw=0;
	for(i=0;i<len1||i<len2||jw;i++)
	{
		c[i]=a[i]+b[i]+jw;
		if(c[i]>9) c[i]-=10,jw=1;
		else jw=0;
	}
}
void minus0()
{
	short tw=0;
	for(i=0;i<len1||i<len2||tw;i++)
	{
		c[i]=a[i]-b[i]-tw;
		if(c[i]<0) c[i]+=10,tw=1;
		else tw=0;
	}
}
int main()
{
	int t;
	char temp;
	while(1)
	{
		len1=len2=0;
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		memset(c,0,sizeof(c));
		if(scanf("%c",&temp)==EOF) break;
		if(temp=='-')         //a为负
		{
			mark1=false;
		}
		else                  //a为正
		{
			mark1=true;
			a[0]=temp-'0',len1++;
		}
		while(1)
		{
			scanf("%c",&temp);
			if(temp<'0'||temp>'9') break;
			a[len1++]=temp-'0';
		}
		scanf("%c",&temp);
		if(temp=='-')         //b为负
		{
			mark2=false;
		}
		else                  //b为正
		{
			mark2=true;
			b[0]=temp-'0',len2++;
		}
		while(1)
		{
			scanf("%c",&temp);
			if(temp<'0'||temp>'9') break;
			b[len2++]=temp-'0';
		}
		for(i=0;i<len1/2;i++)
		{
			t=a[i],a[i]=a[len1-1-i],a[len1-i-1]=t;
		}
		for(i=0;i<len2/2;i++)
		{
			t=b[i],b[i]=b[len2-1-i],b[len2-i-1]=t;
		}
		if(mark1&&mark2) plus0();
		else if(mark1&&!mark2)
		{
			if(compare()==2) 
			{
				printf("0\n");
				continue;
			}
			else if(compare()==0) 
			{
				printf("-");
				change();
			}
			minus0();
		}
		else if(!mark1&&mark2)
		{
			if(compare()==2) 
			{
				printf("0\n");
				continue;
			}
			else if(compare()==1) 
			{
				printf("-");
			}
			else change();
			minus0();
		}
		else
		{
			printf("-");
			plus0();
		}
		output();
	} 
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值