#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;
}
HDU 1002 A+B Problem
最新推荐文章于 2020-06-04 20:08:54 发布