实现一个任意长度的整数加法
#include "stdio.h"
#include "math.h"
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}sqStack;
void initStack(sqStack *s)
{
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!s->base)
exit(0);
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
}
void Push(sqStack *s, ElemType e)
{
if (s->top - s->base >= s->stacksize)
{
s->base = (ElemType *)realloc(s->base, (s->stacksize + STACK_INIT_SIZE) * sizeof(ElemType));
if (!s->base)
exit(0);
s->top = s->base + s->stacksize;
}
*(s->top) = e;
s->top ++;
}
void Pop(sqStack *s, ElemType *e)
{
if (s->top == s->base)
return;
*e = *--(s->top);
}
int StackLen(sqStack s)
{
return (s.top - s.base);
}
void ADD(sqStack *s1, sqStack *s2, sqStack *s3)
{
char a1, a2, a3, c = 0;
while(StackLen(*s1) != 0 && StackLen(*s2) != 0)
{
Pop(s1, &a1);
Pop(s2, &a2);
a3 = (a1 - 48) + (a2 - 48) + c + 48;
if (a3 > '9')
{
a3 = a3 -'9' + 47;
c = 1;
}
else
c = 0;
Push(s3, a3);
}
if (StackLen(*s1) != 0)
{
while(StackLen(*s1) != 0)
{
Pop(s1, &a1);
a3 = a1 + c;
if (a3 > '9')
{
a3 = a3 - '9' + 47;
c = 1;
}
else
c = 0;
Push(s3, a3);
}
}
else if(StackLen(*s2) != 0)
{
while(StackLen(*s2) != 0)
{
Pop(s2, &a2);
a3 = a2 + c;
if (a3 > '9')
{
a3 = a3 - '9' + 47;
c = 1;
}
else
c = 0;
Push(s3, a3);
}
}
if (c == 1)
Push(s3, '1');
}
void main()
{
char e;
sqStack s1, s2, s3;
initStack(&s1);
initStack(&s2);
initStack(&s3);
printf("Please input the first integer,and the end of '#'\n");
scanf("%c", &e);
while(e != '#')
{
Push(&s1, e);
scanf("%c", &e);
}
printf("Please input the second integer,and the end of '#'\n");
scanf("%c", &e);
while(e != '#')
{
Push(&s2, e);
scanf("%c", &e);
}
ADD(&s1, &s2, &s3);
printf("The result is:\n");
while(StackLen(s3) != 0)
{
Pop(&s3, &e);
printf("%c", e);
}
printf("\n");
getchar();
}