poj1220

任意进制的转换,看起来简单,但写起来并非想像中的简单,注意基础环节的练习

将M进制转换成N进制数,思路:将M进制数先转换为十进制的数组中,再进行辗转相除,求余数的方法,依次求出N进制的各个位数。

/* Wrote by Dream Chen, 2010-12-23 */

#include <iostream>

using namespace std;

int m = 0;

int k = 0;

char data[500];

char res[500];

void Solve();

inline int CharToInt(char ch)
{
	if (ch >= '0' && ch <= '9')
	{
		ch = ch - '0';
	}
	else if (ch >= 'A' && ch <= 'Z')
	{
		ch = 10 + ch - 'A';
	}
	else if(ch >= 'a' && ch <= 'z')
	{
		ch = 36 + ch - 'a';
	}
	return ch;
}

inline char IntToChar(char ch)
{
	if (ch >= 0 && ch <= 9)
	{
		ch = '0' + ch - 0;
	}
	else if (ch >= 10 && ch <= 35)
	{
		ch = 'A' + ch - 10;
	}
	else if (ch >= 36 && ch <= 61)
	{
		ch = 'a' + ch - 36;
	}
	return ch;
}

int main()
{
	//freopen("input.txt","r",stdin);
	int n = 0;
	
	scanf("%d",&n);
	
	while (n--)
	{
		memset((void*)data,0,sizeof(data));
		memset((void*)res,0,sizeof(res));
		scanf("%d%d%s",&m,&k,data);
		printf("%d %s\n%d ",m,data,k);
		Solve();
		printf("\n\n");
	}
	
	return 0;
	
}



void Solve()
{
	int len = strlen(data);
	for (int i = 0; i < len; ++i)
	{
		data[i] = CharToInt(data[i]);
	}
	
	int j = 0;
	
	while(len > 0) 
	{
		int s = 0;
		bool flag = false;
		int start = -1;
		//下一次辗转相除时, data中剩下的真实长度,除得的商按从位置0开始往data里面写
		for (int i = 0; i < len; ++i)
		{
			s = s*m + data[i];
			if (s/k)
			{
				flag = true;
			}
			if (flag)
			{
				data[++start] = s/k;
				s %= k;
			}
		}
		len = ++start;
		res[j] = s;
		++j;
	}
	
	for (int i = j - 1; i >= 0; --i)
	{
		printf("%c",IntToChar(res[i]));
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值