进制转换
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
输入一个十进制数N,将它转换成R进制数输出。
Input
输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R != 10)。
Output
为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。
Example Input
7 2
23 12
-4 3
Example Output
111
1B
-11
Hint
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef struct
{
char data[40];
int top;
}Sqstack;
bool sempty(Sqstack *s)//判断栈是否为空
{
return (s->top==-1);
}
void push(Sqstack *s,char 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(long long num,long long r)
{
int flag=0;
if(num==0)
{
printf("0\n");
return;
}
if(num<0)
{
flag=1;
num=-num;
}
Sqstack *p;
p=(Sqstack *)malloc(sizeof(Sqstack));
p->top=-1;
while(num!=0)
{
int rem1;
rem1=num%r;
push(p,rem1);
num=num/r;
}
if(flag==1)
printf("-");
while(!sempty(p))
{
int rem2;
rem2=pop(p);
if(r>10)//大于十的进制数的输出。
{
if(rem2==10)
{
rem2='A';
printf("%c",rem2);
}
else if(rem2==11)
{
rem2='B';
printf("%c",rem2);
}
else if(rem2==12)
{
rem2='C';
printf("%c",rem2);
}
else if(rem2==13)
{
rem2='D';
printf("%c",rem2);
}
else if(rem2==14)
{
rem2='E';
printf("%c",rem2);
}
else if(rem2==15)
{
rem2='F';
printf("%c",rem2);
}
else
printf("%d",rem2);
}
else//小于十的进制数输出。
printf("%d",rem2);
}
printf("\n");
}
int main()
{
long long num,r;
while(~scanf("%lld %lld",&num,&r))
{
change(num,r);
}
return 0;
}