任意长度的整数加法C语言代码

实现一个任意长度的整数加法

 

#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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值