利用栈来处理大数加法

  • 大数加法问题
    在这里插入图片描述
  • 用栈来模拟
    因为两个数串由高位到低位输入,由低位到高位计算,最后由高位到低位输出,故选择用栈模拟
#include <iostream>
#include <cstring>

#define MAXSIZE 200

using namespace std;   //使用名称空间std

typedef struct
{
	int* top;
	int* base;
	int stacksize;
}Sqstack;

int main()
{//大数加法(栈)
	int Initstack(Sqstack &OPND);
	int Push(Sqstack &OPND, int e);
	int Pop(Sqstack &OPND);
	Sqstack str1, str2, sum;
	char num1[200], num2[200];
	int T;
	int i;
	int flag=0;   //计数器
	char a;
	int b1, b2, c;
	int temp=0;   //进位标志
	cin >> T;
	while (flag < T)
	{
		temp = 0;
		Initstack(str1);
		Initstack(str2);
		Initstack(sum);
		//栈初始化完成
		memset(num1, '\0', sizeof(num1));
		memset(num2, '\0', sizeof(num2));
		cin >> num1 >> num2;
		i = 0;
		a = num1[i++];
		while (a != '\0')
		{//入栈
			b1 = a - '0';
			Push(str1, b1);
			a = num1[i++];
		}
		i = 0;
		a = num2[i++];
		while (a != '\0')
		{//入栈
			b2 = a - '0';
			Push(str2, b2);
			a = num2[i++];
		}

		while (str1.base != str1.top&&str2.base != str2.top)
		{//两栈均非空
			b1 = Pop(str1);
			b2 = Pop(str2);
			c = b1 + b2 + temp;
			if (c > 9)
			{
				c = c - 10;
				Push(sum, c);
				temp = 1;
			}
			else
			{
				Push(sum, c);
				temp = 0;
			}
		}
		while (str1.base != str1.top)
		{//栈str1非空
			b1 = Pop(str1) + temp;
			if (b1 > 9)
			{
				b1 = b1 - 10;
				Push(sum, b1);
				temp = 1;
			}
			else
			{
				Push(sum, b1);
				temp = 0;
			}
		}
		while (str2.base != str2.top)
		{//栈str2非空
			b2 = Pop(str2) + temp;
			if (b2 > 9)
			{
				b2 = b2 - 10;
				Push(sum, b2);
				temp = 1;
			}
			else
			{
				Push(sum, b2);
				temp = 0;
			}
		}
		if (temp)        //最后进位
			Push(sum, temp);

		while (sum.base != sum.top)
		{
			cout << Pop(sum);
		}
		cout << endl;

		delete[] str1.base;
		delete[] str2.base;
		delete[] sum.base;
		//栈销毁完成
		flag++;
	}
	return 0;
}

//数栈Sqstack操作函数
int Initstack(Sqstack &OPND)
{//数栈初始化
	OPND.base = new int[MAXSIZE];
	if (!OPND.base)  return 0;
	OPND.top = OPND.base;
	OPND.stacksize = MAXSIZE;
	return 1;
}

int Push(Sqstack &OPND, int e)
{//数栈入栈
	if (OPND.top - OPND.base == OPND.stacksize)  return 0;           //判断是否栈满
	*OPND.top++ = e;                                                //e入栈,栈顶指针+1
	return 1;
}

int Pop(Sqstack &OPND)
{//数栈出栈
	int e;
	if (OPND.top == OPND.base)   return 0;                         //判断是否栈空
	e = *--OPND.top;                                               //栈顶指针-1,e存储栈顶元素
	return e;
}

猜你喜欢

转载自blog.csdn.net/qq_40432881/article/details/82945535