HDU 1002 A+B Problem

#include <iostream>
using namespace std;
typedef char ElemType;
#define MaxSize 1001


typedef struct{//栈的顺序存储
	ElemType data[MaxSize];
	int top;
}SqStack;

void InitStack(SqStack *&s){//初始化栈
	s = new SqStack;
	s->top = -1;
}

int Push(SqStack *&s, ElemType e){//进栈
	if(s->top == MaxSize -1)
		return 0;
	s->top++;
	s->data[s->top] = e;
	return 1;
}

int Pop(SqStack *&s, ElemType &e){//出栈
	if(s->top == -1)
		return 0;
	e = s->data[s->top];
	s->top--;
	return 1;
}

int StackLength(SqStack *s){//栈长
	return (s->top + 1);
}

void Add(SqStack *s1, SqStack *s2, SqStack *&s3)//s1是长的栈,s2是短的栈
{
	ElemType e1, e2, e3;//出栈的字符存在e1, e2, e3中
	int a, b = 0; //a是两数相加的和,b是进位
	int s2_length = StackLength(s2);//短栈的长度
	for(int i = 0; i < s2_length; i++){
		Pop(s1, e1);//s1出栈,存在e1中
		Pop(s2, e2);//s2出栈,存在e2中
		a = (int)(e1 - 48) + (int)(e2 - 48);//e1,e2中的两数相加
		a = a + b;//加上进位
		if(b == 1){//当进位为1是,变为0
			b--;
		}
		if(a >= 10){//当和a大于10时,a-10,b++,将数字入栈
			a = a - 10;
			b++;
			e3 = (char)(a + 48);
			Push(s3, e3);
		}
		else{
			e3 = (char)(a + 48);
			Push(s3, e3);
		}
	}

	int s1_s2_length = (StackLength(s1) - StackLength(s2));//s1是长栈,s2是短栈,相减求出剩余的数字
	
	if(s1_s2_length > 0){
		for(i = 0; i < s1_s2_length; i++){
			Pop(s1, e1);//当长栈中的数字全部出栈
			a = (int)(e1 - 48);
			a = a + b;
			if(b == 1){
				b--;
			}
			if(a >= 10){//当a为超过10的数字是,变为个位数
				a = a - 10;
				b++;
				e3 = (char)(a + 48);
				Push(s3, e3);
			}
			else{//当a小于10,直接压栈
				e3 = (char)(a + 48);
				Push(s3, e3);
			}
		}
	}
	if(b == 1){//当s1全部出栈后,假如进位==1,进行入栈'1'.
		Push(s3, '1');
	}

}



int main(void)
{
	int n;
	while(cin >> n)
	{
		for(int i = 0; i < n; i++)
		{
			ElemType a[1000] = {0}, b[1000]	= {0};
			cin >> a >> b;
			SqStack *s1, *s2, *s3;
			InitStack(s1);
			InitStack(s2);
			InitStack(s3);
			for(int j = 0; a[j] != '\0'; j++)
			{
				Push(s1, a[j]);

			}
			for(int k = 0; b[k] != '\0'; k++)
			{
				Push(s2, b[k]);
			}

			if(StackLength(s1) >= StackLength(s2)){
				Add(s1, s2, s3);//s1是长的栈,s2是短的栈
			}
			else if(StackLength(s1) < StackLength(s2)){
				Add(s2, s1, s3);
			}
			


			ElemType e;
			int s1_length = StackLength(s1), s2_length = StackLength(s2), s3_length = StackLength(s3);
			cout << "Case " << i+1 << ":" << endl;
			cout << a;
			cout << " + ";
			cout << b;
			cout << " = ";

			for(int z = 0; z < s3_length; z++){
				Pop(s3, e);
				cout << e;
			}
			cout << endl;
			if(i != (n-1)){
				cout << endl;
			}
		}		

	}
	
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值