poj 1220 NUMBER BASE CONVERSION(短除法进制转换)

时间:2021-02-17 05:42:48

题目连接:1220 NUMBER BASE CONVERSION

题目大意:给出两个进制oldBase 和newBase, 以及以oldBase进制存在的数。要求将这个oldBase进制的数转换成newBase进制的数。

解题思路:短除法,只不过时直接利用了高精度的除法运算, 并且将以前默认的*10换成的*oldBase。

#include <stdio.h>
#include <string.h>
const int N = 1005;
int newBase, oldBase, n, cnt, num[N];
char str[N]; int getnum(char c) {
if (c >= '0' && c <= '9')
return c - '0';
else if (c >= 'A' && c <= 'Z')
return c - 'A' + 10;
else
return c - 'a' + 36;
} char getchar(int c) {
if (c >= 0 && c <= 9)
return '0' + c;
else if (c >= 10 && c < 36)
return 'A' + c - 10;
else
return 'a' + c - 36;
} void change() {
memset(num, 0, sizeof(num));
n = strlen(str);
for (int i = 0; i < n; i++)
num[i] = getnum(str[i]);
} void solve() {
int flag = 1;
memset(str, 0, sizeof(str));
cnt = 0; while (flag) {
int t = 0, k;
flag = 0;
for (int i = 0; i < n; i++) {
k = num[i] + t * oldBase;
num[i] = k / newBase;
if (num[i]) flag = 1;
t = k % newBase;
}
str[cnt++] = getchar(t);
}
} int main() {
int cas;
scanf("%d", &cas);
while (cas--) {
scanf("%d%d%s", &oldBase, &newBase, str); printf("%d %s\n", oldBase, str); change();
solve(); printf("%d ", newBase);
for (int i = cnt - 1; i >= 0; i--)
printf("%c", str[i]);
printf("\n");
if (cas) printf("\n");
}
return 0;
}