HDUOJ 2031

进制转换

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12130    Accepted Submission(s): 6844


Problem Description
输入一个十进制数N,将它转换成R进制数输出。
 

Input
输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R<>10)。
 

Output
为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。
 

Sample Input
7 2 23 12 -4 3
 

Sample Output
111 1B -11
 

我最初的代码:
#include <iostream>
using namespace std;
int main()
{
	int r,n,a;
	char *top,base;
	while(cin>>n>>r)
	{
		top=&base;
		if(n<0)
		{
			printf("-");
			n=0-n;
		}
		while(n)
		{
			a=n%r;
			if(a<10)
			{ 
				*top=a+'0';
			}
			else 
			{
				*top=(a-10)+'A';
			}
			n/=r;
			top++;
		}
		top--;
		while(top!=&base)
		{
			printf("%c",*top);
			top--;
		}
		printf("%c\n",*top);
	}
	return 0;
}
但当n达到一定值后会输出乱码,我推测是因为top申请连续的空间时出错。
由于n是32位整数,范围是-2^31~2^31-1,故n以2进制表示时的位数不超过32位(2进制的第32位对应十进制2^31),故改为用ch[32]存储结果。
AC代码:
#include <iostream>
using namespace std;
int main()
{
	int r,n,a,i;
	char ch[32];
	while(cin>>n>>r)
	{
		if(n<0)
		{
			printf("-");
			n=0-n;
		}
		for(i=0;n;i++)
		{
			a=n%r;
			if(a<10)
			{ 
				ch[i]=a+'0';
			}
			else 
			{
				ch[i]=(a-10)+'A';
			}
			n/=r;
		}
		for(i--;i>=0;i--)
		{
			printf("%c",ch[i]);
		}
		printf("\n");
	}
	return 0;
}




posted on 2012-03-17 09:57  铁树银花  阅读(208)  评论(0编辑  收藏  举报

导航