数据结构实验之栈与队列一:进制转换
Problem Description
输入一个十进制非负整数,将其转换成对应的 R (2 <= R <= 9) 进制数,并输出。
Input
第一行输入需要转换的十进制非负整数;
第二行输入 R。
Output
输出转换所得的 R 进制数。
Example Input
1279 8
Example Output
2377
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
typedef int elemtype;
typedef int status;
#define MAXSIZE 100
#define OVERFLOW -2
#define another 50
#define true 1
#define false 0
typedef struct{
elemtype *base;
elemtype *top;
int stacksize;
}Sqstack;
status isEmpty(Sqstack &S){
if(S.top == S.base)
return true;
else
return false;
}
void initStack(Sqstack &S){
S.base = new elemtype[MAXSIZE];
S.top = S.base;
S.stacksize = MAXSIZE;
}
elemtype getTop(Sqstack &S){
if(S.base == S.top)
return false;
else
return *(S.top-1);
}
void Push(Sqstack &S, elemtype e){
if(S.top-S.base >= S.stacksize){
S.base = (elemtype *)realloc(S.base,(another+S.stacksize)*sizeof(elemtype));
S.top = S.base + S.stacksize;
S.stacksize += another;
}
*S.top++ = e;
}
int Pop(Sqstack &S, elemtype &e){
return e = *--S.top;
}
int main(){
int n, r;
Sqstack S;
initStack(S);
scanf("%d %d", &n, &r);
if(n < 0)
printf("-"),n = -n;
if(n == 0)
printf("0");
while(n){
int cnt = n%r;
n = n/r;
Push(S,cnt);
}
while(!isEmpty(S)){
int cnt = Pop(S, cnt);
printf("%d",cnt);
}
printf("\n");
}