问题描述:
已知:位数为K(0 < K <200)的N进制数P(2 ≤ N ≤62),该数由0-9, A-Z, a-z组成,其中A-Z代表10-35,a-z代表36-61
求:转换为M进制(2 ≤ M ≤62)后的新数Q
输入:第1行为case数T;第2至第T+1行为T个case,每行输入均为N、M以及P,用空格分隔
输出:采用以下形式输出
N P
M Q
空行
……
Sample Input:
1
62 2 abcdefghiz
Sample Output:
62 abcdefghiz
2 11011100000100010111110010010110011111001001100011010010001
思路是这样的,如十进制数83对应的二进制是1010011,八进制是123,
现在把1010011转化为八进制数,从1010011(7位)的高位开始进行计算:
1、0*2 +1 = 1(小于8); 0
2、1*2+0 = 2;(小于8) 00
3、2*2+1 = 5(小于8); 000
4、5*2+0=10(大于8) 10/8 等于 8 余 2; 0001
5、2*2 +0 = 4(小于8); 00010
6、4*2+1 = 9(大于8); 9/8 等于 1 余 1 000101
7、1*2 +1 = 3 (小于8) 最终余数 3 0001010(非全为0)
第二次从上面得出的0001010的非零高位开始计算(即计算1010(4位))
1、0*2 +1 = 1(小于8); 0
2、1*2 +0 = 2(小于8); 00
3、2*2 +1 = 5 (小于8); 000
4、5*2 + 0 = 10(大于8); 10/8 = 1 等于 1 余 2(小于8) 最终余2 0001(非全为0)
第三次同理计算1(1为)
1、0*2+1 = 1(小于8) 最终余 1 0(全为0,表示完成转换)
倒排最终余数即得到所求的八进制数:123
AC代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int maxlen = 210;
int n,i,j,k,begin,end,top,last,cur;
char strb[maxlen], stre[maxlen], turn[maxlen];
int char_to_int(char ch){
int n;
if(ch >= '0' && ch <= '9') n = ch - '0';
else if(ch >= 'A' && ch <= 'Z') n = ch - 'A' + 10;
else n = ch - 'a' + 36;
return n;
}
char int_to_char(int n){
char ch;
if(n >= 0 && n <= 9) ch = '0' + n;
else if(n >= 10 && n <= 35) ch = 'A' + n - 10;
else ch = 'a' + n - 36;
return ch;
}
bool allzero(char str[]){
for(int i = 0; str[i]; i++){
if(str[i] != '0') return false;
}
return true;
}
int main()
{
scanf("%d", &n);
while(n--){
scanf("%d%d%s", &begin, &end, strb);
printf("%d %s\n", begin, strb);
top = 0;
do{
last = 0;
for(i = 0; i < strlen(strb); i++){
cur = last*begin + char_to_int(strb[i]);
if(cur < end){
last = cur;
turn[i] = '0';
continue;
}
else{
turn[i] = int_to_char(cur/end);
last = cur % end;
}
}
turn[i] = '\0';
stre[top++] = int_to_char(last);
for(j = 0; turn[j] ; j++){
if(turn[j] != '0')
break;
}
for(k = j;turn[k];k++){
strb[k - j] = turn[k];
}
strb[k - j] = '\0';
}while(allzero(strb) == false);
printf("%d ",end);
for(int i = top-1; i >= 0; i--) //逐位逆推得转换后的新数
printf("%c", stre[i]);
printf("\n\n");
}
return 0;
}