栈的应用:进制转换

栈是先进后出的线性表,具体的栈的概念同学们可以参考数据结构相关较教材,下面,我们来讨论一个应用栈的具体实例:进制转化。

//利用栈解决进制转换问题
#include<iostream>
#include<stdlib.h>
using namespace std;
int const maxlen = 20;

template <typename T> 
class Stack
{
private:
	T remainder[maxlen];
	int count;
public:
	Stack();
	bool is_empty() const;
	bool is_full() const;
	bool push(T n);
	bool get_top(T &n);
	bool pop();
};
template <typename T>
Stack<T>::Stack()
{
	 count = 0;
}
template <typename T>
bool Stack<T>::is_empty() const
{
	if (count == 0)
		return true;
	return false;
}
template <typename T>
bool Stack<T>::is_full() const
{
	if (count == maxlen - 1)
		return true;
	return false;
}
template <typename T>
bool Stack<T>::push(T n)
{
	if (is_full())
		return false;
	remainder[count] = n;
	count++;
	return true;
}
template <typename T>
bool Stack<T>::get_top(T &n)
{
	if (is_empty())
		return false;
	n = remainder[count - 1];
	return true;
}
template <typename T>
bool Stack<T>::pop()
{
	if (is_empty())
		return false;
	count--;
	return true;
}

void Convert(int dec, int n)
{
	Stack<int>S;
	int mod, x;//x表示从栈中取出的余数。
	char y;
	if (dec >= 0 && n >= 2 && n <= 16)
	{
		while (dec)
		{
			mod = dec % n;
			S.push(mod);
			dec = dec / n;
		}
		while (!S.is_empty())
		{
			S.get_top(x);
			S.pop();
			if (x <= 9)
				cout << x;
			else {
				y = x + 55;
				cout << y;
			}
		}
		cout << endl;
	}
}

int main()
{
	int dec, n;
	cout << "将十进制数dec转化为n进制数,请输入dec(dec>=0)和n(2<=n<=16)的值:" << endl;
	cin >>dec>>n;
	Convert(dec, n);
	system("pause");
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值