题解
参考博文
代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// 根据进制,把字符串转为实际数字
long long convert(string num,long long radix){
long long res=0;
int exp;//最低位的指数
// auto自动判断类型,rbegin()是最后一个字符,rend()是第一个字符
for(auto it=num.rbegin();it!=num.rend();it++){
// '0'-'9',注意这里要加*才能得到值
if(isdigit(*it)){
res+=(*it-'0')*pow(radix,exp++);
}else{
res+=(*it-'a'+10)*pow(radix,exp++);
}
}
return res;
}
long long findRadix(string num,long long target){
// 找到字符串形式的n2中最大的那个字符,注意这里要加*才能得到值
char maxChar=*max_element(num.begin(),num.end());
// 转为数字加1,就是 进制的下限
long long low=(isdigit(maxChar)?maxChar-'0':maxChar-'a'+10)+1;
// 进制的上限就是 n1
long long high=max(low,target);
// 二分法
while(low<=high){
long long mid=low+(high-low)/2;
long long temp=convert(num,mid);
// temp < 0,代表得到的数字越界,temp > target都代表当前进制太大,需要调整上限
if(temp<0||temp>target){
high=mid-1;
}else if(temp==target){
return mid;
}else{
low=mid+1;
}
}
return -1;
}
int main()
{
string n1,n2;
int tag;
long long radix;
cin>>n1>>n2>>tag>>radix;
long long res=tag==1?findRadix(n2,convert(n1,radix)):findRadix(n1,convert(n2,radix));
if(res==-1)
cout<<"Impossible";
else
cout<<res;
return 0;
}