POJ1220 Number Base Conversion 数学

这篇博客详细介绍了如何解决POJ1220数制转换问题,通过数学分析和算法讲解,展示了从a进制转换为b进制的具体步骤,特别提到了当输入为0时的处理方法,并提供了获得正确答案(AC)的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值