利用栈能将一个十进制整数化为36进制以内的任意进制数(十个数字加26个大写字母作为基数),整数和转化的进制由用户输入。
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX_N = 40;
typedef int ElemType;
//定义栈的结构体
typedef struct Stack {
ElemType data[MAX_N];
int top;
}SqStack;
/*--------------------------------栈的基本操作----------------------------------------------*/
//1.初始化栈
void InitStack(SqStack*& s)
{
s = new SqStack;
s->top = -1;
}
//2.销毁栈
void DestroyStack(SqStack*& s)
{
free(s);
}
//3.判断栈是否为空
bool EmptyStack(SqStack* s)
{
return (s->top == -1);
}
//4.进栈操作
bool PushStack(Stack*& s, ElemType e)
{
if (s->top == MAX_N) return false;
s->top++;
s->data[s->top] = e;
return true;
}
//5.出栈操作
bool PopStack(SqStack*& s, ElemType& e)
{
if (s->top == -1)return false;
e = s->data[s->top];
s->top--;
return true;
}
//6.取栈顶元素
bool Gettop(SqStack* s, ElemType& e)
{
if (s->top = -1)return false;
e = s->data[s->top];
return true;
}
/*---------------------------------------------------------------------------------*/
//给数据做变换
int Conersion_2(int num)
{
if (num < 10)
return num ;
else
return num - 10 + 'A';
}
//将数据转化成任意R进制并输出:
void ConersionBase(ElemType e, int R, SqStack *&s)
{
if (e == 0)
cout << '0';
else {
while (e)
{
PushStack(s, Conersion_2(e%R));
e /= R;
}
}
while (s->top != -1)
{
ElemType res;
PopStack(s, res);
if (res < 10)
cout << res;
else
printf("%c", res);
}
}
int main()
{
int data, R;
cout << "输入待转换的数据以及需要转换的进制:" << endl;
cin >> data >> R;
SqStack* s;
InitStack(s);
cout << '(';
ConersionBase(data, R, s);
cout << ')' << R << endl;
return 0;
}