PAT Advanced Level 1010 Radix
作者:互联网
1. 问题描述
2. Solution
1、思路分析
分析:convert函数:给定一个数值和一个进制,将它转化为10进制。转化过程中可能产生溢出
find_radix函数:找到令两个数值相等的进制数。在查找的过程中,需要使用二分查找算法,如果使用当前进制转化得到数值比另一个大或者小于0,说明这个进制太大~
2、代码实现
// PAT Advance Level 1010
// Ye Qiu
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
long long convert2decimal(const string &n, long long radix) {
long long res = 0, cur;
int index = 0;
for (auto it = n.rbegin(); it != n.rend(); it++){
cur = isdigit(*it) ? *it - '0' : *it - 'a' + 10;
res += cur * pow(radix, index++);
}
return res;
}
long long find_radix(const string &n, long long num) {
char it = *max_element(n.begin(), n.end());
long long lo = (isdigit(it) ? it - '0' : it - 'a' + 10) + 1;
long long hi = max(num, lo);
while (lo <= hi) {
long long mid = (lo + hi) / 2;
long long t = convert2decimal(n, mid);
if (t == num) return mid;
else if (t < 0 || t > num) hi = mid - 1;
else lo = mid + 1;
}
return -1;
}
int main() {
string n1, n2;
long long tag = 0, radix = 0, result_radix;
cin >> n1 >> n2 >> tag >> radix;
result_radix = tag == 1 ? find_radix(n2, convert2decimal(n1, radix)) :
find_radix(n1, convert2decimal(n2, radix));
if (result_radix == -1) {
printf("Impossible");
} else {
printf("%lld", result_radix);
}
return 0;
}
3、复杂度分析
时间复杂度:
标签:radix,PAT,进制,lo,long,Radix,result,1010,find 来源: https://www.cnblogs.com/junstat/p/16197474.html