进制转换,用栈实现
今天看数据结构中的栈解决进制转换的问题,实现了一下。
linux下gdb调程序感觉还是会有一点麻烦啊,主要是不能一下子看到很多变量的值,要一个个地去p,好郁闷
代码如下:
stack.cpp
//用于实现栈的操作
#include
using namespace std;
//const int MAX=100;//栈最大长度值为100,用数组实现栈
//写成模板类是为了方便我以后使用
template
class mStack{
private:
enum {MAX=100};
T arr[MAX];
int Size;
int top;//用于指示栈顶位置
public:
mStack()//构建空栈
{
top=-1;//下标为-1则为空栈
Size=0;
}
bool isEmpty()
{
return top==-1;
}
bool isFull()
{
return top==MAX-1;
}
bool Push(T &item)
{
if(isFull())
{
cout<<”stack is full!”<<endl;
return false;
}
//++top;
//arr[++top]=item;
arr[++top]=item;//因为下标从-1开始,使用前+1
//cout<<”this “<<top<<” item push values is :”<<arr[top]<<endl;
Size++;
return true;
}
bool Pop(T &item)
{
if(isEmpty())
{
cout<<”stack is empty!”<<endl;
return false;
}
item=arr[top–];//因为下标从-1开始,top指向当前最后一个元素,使用后-1
//cout<<”this “<<top<<” item pop values is :”<<arr[top]<<endl;
Size–;
return true;
}
int size()
{
return Size;
}
};
translate.cpp
#include
#include “stack.cpp”
using namespace std;
//static const int MAXSIZE=100;//用于顺序存放转换进制之后的值
//由于进制转换的特点,可以先让余数入栈,然后再出栈来求得转换后的值,接口如下,
//如果想返回一个值,可以改变接口的规则
void translate(int target,int n)//target是要转换的值,n为转换为多少进制
{
mStack
int yushu;
//核心代码,余数入栈
while(target!=0)
{
yushu=target%n;
my.Push(yushu);
/*if(my.Push(yushu))
cout<<”push success!”<<endl;
else
cout<<”push error!”<<endl;*/
//cout<<”stack size=”<<my.size()<<endl;
target=target/n;
}
/*
if(target%n==0)//最后一个
{
yushu=target%n;
my.Push(yushu);//将最后一个target%n入栈
}*/
//outpue
cout<<”the “<<target<<” translate to “<<n<<” is:”<<endl;
while(!my.isEmpty())
{
int temp;
my.Pop(temp);
//if(my.Pop(temp))
//cout<<”pop success!”<<endl;
cout<<temp;
}
cout<<endl;
}
test.cpp
#include
#include “translate.cpp”
using namespace std;
int main()
{
int target;
int n;
cout<<”please input two numbers;first for target,second for n:”;
while(cin>>target>>n)
{
translate(target,n);
//cin.get();
}
return 0;
}
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/进制转换,用栈实现/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!