进制转换 - 寻找最小进制数 - C++ 实现
【解题思路】 题目要求找到一个进制,使得给定的字符串形式的正整数可以在该进制下表示。假设该进制为x进制,则对应的数位上的数的范围为0∼x−1。而字符串中的最大数位对应的字符对应的数值就是x-1,所以我们只需要找到字符串中的最大数位对应的字符的数值,然后加1即可得到x的值。
【伪代码】
- 读入字符串s
- 初始化max_digit为0
- 遍历字符串s中的每个字符c 4. 如果c是数字字符 5. 将c转换为整数n 6. 更新max_digit为max(max_digit, n) 7. 否则 8. 将c转换为整数n 9. 更新max_digit为max(max_digit, n-55)
- 输出max_digit+1
【复杂度分析】 时间复杂度:O(n),其中n为字符串的长度。 空间复杂度:O(1)。
【C++ 代码实现】
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
int max_digit = 0;
for (char c : s) {
if (isdigit(c)) {
max_digit = max(max_digit, c - '0');
} else {
max_digit = max(max_digit, c - 'A' + 10);
}
}
cout << max_digit + 1 << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pPU8 著作权归作者所有。请勿转载和采集!