进制转换
Time Limit: 1000MS Memory limit: 65536K
题目描述
输入一个十进制数N,将它转换成R进制数输出。
输入
输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R<>10)。
输出
为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。
示例输入
7 2
23 12
-4 3
示例输出
111
1B
-11
提示
来源
HDOJ
示例程序
#include<stdio.h>
#include<string.h>
char arr[1000];
int main()
{
int n,r;
int top,f,t;
while(~scanf("%d %d",&n,&r))
{
top = 0;
f = 0;
if(n == 0)
{
printf("0\n");
}
else
{
if(n < 0)
{
n = -n;
f = 1;
}
while(n)
{
t = n%r;
if(t >= 10)
arr[top++] = t - 10 +'A';
else
arr[top++] = t + '0';
n = n/r;
}
if(f)
printf("-");
for(int i = top-1;i >= 0;i--)
{
printf("%c",arr[i]);
}
printf("\n");
}
}
return 0;
}
用的栈
#include<stdio.h>
#include<stdlib.h>
#define stackmax 1000
#define stacknum 1000
typedef struct
{
char *top;
char *base;
int stacksize;
}stack;
int initstack(stack &s)
{
s.base = (char *)malloc(stackmax*sizeof(char *));
if(!s.base) exit(0);
s.top = s.base;
s.stacksize = stackmax;
return 1;
}
int push(stack &s,char e)
{
if(s.top - s.base > s.stacksize)
{
s.base = (char *)realloc(s.base,(s.stacksize+stacknum)*sizeof(char));
if(!s.base) exit(0);
s.top = s.base+s.stacksize;
s.stacksize += stacknum;
}
*s.top++ = e;
return 1;
}
void show(stack &s,int f)
{
if(f)
printf("-");
while(s.top != s.base)
{
s.top--;
printf("%c",*s.top);
}
printf("\n");
}
int main()
{
stack s;
int n,r,t;
char e;
while(~scanf("%d %d",&n,&r))
{
int f = 0;
if(n == 0)
{
printf("0\n");
}
else
{
if(n < 0)
{
n = -n;
f = 1;
}
initstack(s);
while(n)
{
t = n%r;
if(t >= 10)
e = t - 10 + 'A';
else
e = t + '0';
push(s,e);
n = n/r;
}
show(s,f);
}
}
return 0;
}
本文介绍了一个进制转换的算法实现,能够将十进制数转换为2到16之间的任意进制数,并提供了两种实现方式:一种是使用数组模拟栈进行转换,另一种是直接使用栈数据结构。
1万+

被折叠的 条评论
为什么被折叠?



