题目链接
http://poj.org/problem?id=1220
分析
设 x x x 是 a a a 进制数, a > 0 a > 0 a>0,
在 a a a 进制下, 令 x x x 不断除以 b b b,将所得余数倒序输出即可将 x x x 转化为 b b b 进制数。
注意输入为 0 0 0 的情况。
AC代码
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
inline int read() {
int num = 0;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9')
num = num * 10 + c - '0', c = getchar();
return num;
}
const int maxb = 1e3 + 5;
struct BigInteger {
int num[maxb], len, base;
BigInteger(int x, int b) {
memset(num, 0, sizeof(num));
len = 1, base = b;
while (x) num[len++] = x % base, x /= base;
if (len > 1) --len;
}
BigInteger operator / (const int& rhs) const {
BigInteger ans = *this;
for (int i = ans.len; i >= 1; --i) {
ans.num[i - 1] += ans.num[i] % rhs * base;
ans.num[i] /= rhs;
}
while (!ans.num[ans.len] && ans.len > 1) --ans.len;
return ans;
}
};
inline int toint(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'Z') return c - 'A' + 10;
return c - 'a' + 36;
}
inline char tochar(int i) {
if (i >= 0 && i <= 9) return i + '0';
if (i >= 10 && i <= 35) return i - 10 + 'A';
return i - 36 + 'a';
}
char s[maxb];
stack<char> ans;
int main() {
int n = read();
while (n--) {
int b1 = read(), b2 = read();
BigInteger x(0, b1);
scanf("%s", s + 1), x.len = strlen(s + 1);
printf("%d %s\n%d ", b1, s + 1, b2);
for (int i = 1; i <= x.len; ++i)
x.num[i] = toint(s[x.len - i + 1]);
while (!(!x.num[1] && x.len == 1)) {
x = x / b2;
ans.push(tochar(x.num[0] / b1)), x.num[0] = 0;
}
if (ans.empty()) putchar('0');
while (!ans.empty()) putchar(ans.top()), ans.pop();
printf("\n\n");
}
return 0;
}