进制转换
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
提示
#include<iostream>
#include<cstdlib>
#include<stdio.h>
using namespace std;
typedef struct
{
int *base;
int *top;
} stack;
void intistack(stack &s)
{
s.base=new int [1100];
if(!s.base)
exit(0);
s.top=s.base;
}
void push(stack &s,int e)
{
*s.top++=e;
}
int empty(stack &s)
{
if(s.top==s.base)
{
return 0;
}
else
return 1;
}
int pop(stack &s)
{
if(s.top==s.base)
return 0;
int a=*--s.top;
return a;
}
void del(stack &s,int n,int m)
{
int e,flag=1;
if(n<0)
{
n=-n;
flag=0;
}
while(n)
{
push(s,n%m);
n=n/m;
}
while(empty(s))
{
e=pop(s);
if(!flag)
{
flag=1;
cout<<"-";
}
if(e>9)
{
printf("%c",e-10+'A');
}
else
cout<<e;
}
}
int main()
{
stack s;
int n,m;
intistack(s);
while(cin>>n>>m)
{
if(n==0)
cout<<0;
else
del(s,n,m);
cout<<endl;
}
return 0;
}
#include<cstdlib>
#include<stdio.h>
using namespace std;
typedef struct
{
int *base;
int *top;
} stack;
void intistack(stack &s)
{
s.base=new int [1100];
if(!s.base)
exit(0);
s.top=s.base;
}
void push(stack &s,int e)
{
*s.top++=e;
}
int empty(stack &s)
{
if(s.top==s.base)
{
return 0;
}
else
return 1;
}
int pop(stack &s)
{
if(s.top==s.base)
return 0;
int a=*--s.top;
return a;
}
void del(stack &s,int n,int m)
{
int e,flag=1;
if(n<0)
{
n=-n;
flag=0;
}
while(n)
{
push(s,n%m);
n=n/m;
}
while(empty(s))
{
e=pop(s);
if(!flag)
{
flag=1;
cout<<"-";
}
if(e>9)
{
printf("%c",e-10+'A');
}
else
cout<<e;
}
}
int main()
{
stack s;
int n,m;
intistack(s);
while(cin>>n>>m)
{
if(n==0)
cout<<0;
else
del(s,n,m);
cout<<endl;
}
return 0;
}
必须要先判断0,否则无限W A;