数据结构实验之栈与队列一:进制转换
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
输入一个十进制非负整数,将其转换成对应的 R (2 <= R <= 9) 进制数,并输出。
Input
第一行输入需要转换的十进制非负整数;
第二行输入 R。
Output
输出转换所得的 R 进制数。
Example Input
1279
8
Example Output
2377
Hint
思路:十进制转化为R进制数,将十进制数%R取余数,然后倒叙输出,用栈储存。
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef struct
{
int data[20];
int top;
}Sqstack;
bool sempty(Sqstack *s)//判断栈是否为空
{
return (s->top==-1);
}
void push(Sqstack *s,int e)//进栈操作
{
s->top++;
s->data[s->top]=e;
}
int pop(Sqstack *s)//出栈操作
{
int e;
if(s->top!=-1)
{
e=s->data[s->top];
s->top--;
}
return e;
}
void change(int num,int r)
{
if(num==0)
printf("0\n");
else
{
Sqstack *p;
p=(Sqstack *)malloc(sizeof(Sqstack));
p->top=-1;
while(num!=0)
{
int rem1;
rem1=num%r;
push(p,rem1);
num=num/r;
}
while(!sempty(p))
{
int rem2;
rem2=pop(p);
printf("%d",rem2);
}
printf("\n");
}
}
int main()
{
int num,r;
while(~scanf("%d %d",&num,&r))
{
change(num,r);
}
return 0;
}