|
进制转换Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 21060 Accepted Submission(s): 11785
Problem Description
输入一个十进制数N,将它转换成R进制数输出。
Input
输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R<>10)。
Output
为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。
Sample Input
Sample Output
|
我们平时做进制转换是 不断的用 那个十进制数不断的取除你要转换的进制 基于这种想法 可以采用递归去做 ,可以省掉空间但是耗费时间 ,在digital里面要有出递归的条件 及 n == 0时出递归 其他的继续递归 另外要在函数里写出你需要的功能 这里采用了 ?
? : 的调用 巧妙的返回字符 N% b - 10 + 'A' 另外的是 N % b + '0'
主函数:
要判断> 0 、= 0 、< 0 的三种情况 依次输出结果即可
源代码: cout 是可以输出字符的 cin 也是可以读入字符的
#include<iostream>
#include<cstdio>
using namespace std;
int b;
void change(int n)
{
char m;
if(n == 0)
return ;
change(n/b);
m =((n%b >9)? n%b -10 +'A' : n%b + '0');
cout<<m;
}
int main()
{
int a;
while(cin>>a>>b)
{
if(a == 0)
cout<<0<<endl;
else if(a > 0)
change(a);
else
{
cout<<"-";
change(-a);
}
cout<<endl;
}
return 0;
}
下面给出 hoj 16 进制转换代码 ,主要是因为前面看不清楚地:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int t, i;
cin>>t;
unsigned int num;
char a[17];
while(t--)
{
memset(a,'0',17);
cin>>num;
i = 1;
while(num)
{
a[i] =((num%16 >9)? num%16 -10 +'A' : num%16 + '0');
i++;
num /=16;
}
for(i = 1; i <=3; i++)
{
cout<<"0x"<<a[2*i]<<a[2*i-1]<<" ";
}
cout<<"0x"<<a[8]<<a[7]<<endl;
}
return 0;
}
博客是很好的总结和记录工具,如果有问题,来不及回复,关注微信公众号:程序员开发者社区,获取我的联系方式,向我提问,也可以给我发送邮件,联系 1275801617@qq.com