title: 261111周一晚 - 进制 author: wu_sir date: 2026-11-11 organization: 河源高级中学 header: title————{title} ———— {author}(organization)footer:起始于:{organization}) footer: 起始于:{date} - - - - - - 第 pageNo页/共{pageNo} 页 / 共 {pageCount} 页 - - - - - - 终止于:${today} keywords:

  • 进制
  • 字符串

进制

比如说有一个 p 进制的数 abc

那么其数值为:a×p2+b×p1+c×p0a \times p^2 + b\times p^1 + c\times p^0,位权表示法

上式可以写作:((0+a)×p+b)×p+c((0 + a)\times p + b) \times p + c

#C1170. 十进制转 p 进制

code
char itoc(int x) {
	if(x <= 9) return x + '0';
	return x - 10 + 'a';
}
void solved() {
	ll n;	cin >> n;
	int p;	cin >> p;
	// 不断地拆解 p 进制下的每一位即可
	string ans = "";	// 最终的答案
	while(n != 0) {
		int c = n % p;	// 在 p 进制下,拆解 n 的最后一位
		n /= p;	// 在 p 进制下,删去 n 的最后一位
		// 对于任意的非 10 进制,只能采用字符串作为存储方式
		ans = itoc(c) + ans;
	}
	cout << ans << endl;
}

#C1171. p 进制转十进制

code
int ctoi(char c) {
	if(c >= '0' && c <= '9') return c - '0';
	return c - 'a' + 10;
}
void solved() {
	int p;
	string s;
	cin >> p >> s;
	ll ans = 0;
	// for(int i = 0; i < s.size(); i ++) {
	// 	char c = s[i];
	for(char c: s) {
		// 从高位到低位依次处理每个数位
		if(c == '-') continue;
		ans = ans * p + ctoi(c);
	}
	if(s[0] == '-') ans = -ans;
	cout << ans << endl;
}

#C1003. 奇怪的进制(平衡三进制)

思路
  • 数码不平衡的进制转换
    • 本质上是 3 进制,但是存在负数数码
  • 对于某一个进制 p 来说,朴素定义:
    • 每一个数码都要在 [0, p-1] 之间
  • 那么如果是 -p 进制,其定义为
    • 每一个数码都要在 [0, |p|-1] 之间
    • 这是因为没有负数码
  • 但是本题,存在负数数码:{-1, 0, 1}
    • 所以需要在运算的过程中,把 [0, 2] 的数码,换算到 {-1, 0, 1} 之间
  • 数码发生变换的问题
    • 数码残缺,需要进行转换
code
	ll n;	cin >> n;
	string ans;
	do {
		int c = n % 3;	// 其取值为 {-2, -1, 0, 1, 2}
		if(c == 2) c = -1;	// 其中 2 数码不存在,替换为 -1 数码
		if(c == -2) c = 1;	// 其中 -2 数码不存在
		n = (n - c) / 3;	// 从中扣除余数后除 3
		if(c == 1) ans = '1' + ans;
		if(c == 0) ans = '0' + ans;
		if(c == -1) ans = '-' + ans;
	} while(n != 0);
	cout << ans << endl;

#C1177. 表格编号法

code
	int op;	cin >> op;
	if(op == 1) {
		string s;	cin >> s;
		int ans = 0;
		for(char c: s) {
			ans = ans * 26 + c - 'A' + 1;
		}
		cout << ans;
	} else {
		int n;	cin >> n;
		string ans;
		while(n != 0) {
			char c = n % 26;	// 余数范围是 [0, 25]
			if(c == 0) c = 26;	// 实际数码范围 [A, Z] 代表 [1, 26]
			n = (n - c) / 26;
			ans = (char)(c - 1 + 'A') + ans;
		}
		cout << ans;
	}

0 条评论

目前还没有评论...