题解 | #进制转换2#
进制转换2
https://www.nowcoder.com/practice/ae4b3c4a968745618d65b866002bbd32
#include <stdio.h>
#include <string.h>
int getNum(char ch) {
if ('0' <= ch && ch <= '9') {
return (int)(ch - '0');
}
else if ('A' <= ch && ch <= 'Z') {
return (int)(ch - 'A' + 10);
}
else {
return (int)(ch - 'a' + 36);
}
}
char getChar(int num) {
if (0 <= num && num <= 9) {
return (char)(num + '0');
}
else if (10 <= num && num <= 35) {
return (char)(num + 'A' - 10);
}
else {
return (char)(num + 'a' - 36);
}
}
int main()
{
int M, N;
char X[100]; //
scanf("%d %d", &M, &N);
scanf("%s", X); // X是M进制,可能包含字母,比如十六进制,14d4
int len = strlen(X);
int X_index = 0;
int new_X[100]; // 目标进制存储
int new_X_index = 0;
while (X_index < len) {
int yushu = 0;
// 模拟除法
for (int i = X_index; i < len; i++) {
int temp = yushu * M + getNum(X[i]); // 以10进制作为中转进制
X[i] = getChar(temp / N);
yushu = temp % N;
}
new_X[new_X_index++] = getChar(yushu);
// 前面是0的跳过
for (int i = X_index; ; i++) {
if (X[i] != '0' || i > len) {
X_index = i;
break;
}
}
}
// 打印目标进制
for (int i = new_X_index - 1; i >= 0; i--)
{
printf("%c", new_X[i]);
}
printf("\n");
}