1010 Radix (25分)
分析
二分法搜索目标进制,不失一般性,假设tag=1,初始的左边界设为b各位中最小数字加一,右边界设为a
代码
#include<iostream>
#include<string>
using namespace std;
long long int getnum(string s, int d) {
long long int a = 0, z = 1;
for (int i = s.size() - 1; i >= 0; --i, z *= d) {
int aa = (s[i] <= '9' && s[i] >= '0') ? (s[i] - '0') : (s[i] - 'a' + 10);
a += aa * z;
if (a < 0 || z < 0)return -1;
}
return a;
}
int get_lower_bound(string s) {
int m = 0;
for (int i = 0; i < s.size(); ++i) {
int d = (s[i] <= '9' && s[i] >= '0') ? (s[i] - '0') : (s[i] - 'a' + 10);
m = (m < d) ? d : m;
}
return m + 1;
}
int main() {
string sa, sb;
int tag, d;
cin >> sa >> sb >> tag >> d;
if (tag == 2)swap(sa, sb);
long long int a = getnum(sa, d), b;
long long lower_bound = get_lower_bound(sb), upper_bound = a, mid;
while (upper_bound >= lower_bound) {
mid = (lower_bound + upper_bound) / 2;
b = getnum(sb, mid);
if (b >= a || b < 0)upper_bound = mid - 1;
else lower_bound = mid + 1;
}
b = getnum(sb, lower_bound);
if (b != a)printf("Impossible\n");
else printf("%lld\n", lower_bound);
return 0;
}