Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is “yes”, if 6 is a decimal number and 110 is a binary number.
Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.
Input Specification:
Each input file contains one test case. Each case occupies a line which contains 4 positive integers:
N1 N2 tag radix
Here N1 and N2 each has no more than 10 digits. A digit is less than its radix and is chosen from the set {0-9, a-z} where 0-9 represent the decimal numbers 0-9, and a-z represent the decimal numbers 10-35. The last number “radix” is the radix of N1 if “tag” is 1, or of N2 if “tag” is 2.
Output Specification:
For each test case, print in one line the radix of the other number so that the equation N1 = N2 is true. If the equation is impossible, print “Impossible”. If the solution is not unique, output the smallest possible radix.
Sample Input 1:
6 110 1 10
Sample Output 1:
2
Sample Input 2:
1 ab 1 2
Sample Output 2:
Impossible
分析:
进制转化并不难。不同进制数字的大小比较,一般先把它们转化为10进制。
主要是一些细节要注意:比如要用long long,进制大了容易溢出。
二分查找的上下限:下限很好确定,就是最大的digit加1;下限是已知进制的数转化为10进制的值+1.
#include <iostream>
using namespace std;
#include <string>
/*
给出一个数,求它可能的最小进制。
即字符串中最大的数字加1.
*/
long long minRadix(string N){
int ans=0;
for(int i=0;i<N.size();i++){
int D=0;
if(N[i]>='0'&&N[i]<='9') D=N[i]-'0';
else D=N[i]-'a'+10;
if(D>ans) ans=D;
}
return ans+1;
}
/*转10进制*/
long long Convert(string N,long long radix){
long long Output=0;
for(int i=0;i<N.length();i++){
if(N[i]>='0'&&N[i]<='9') Output=(N[i]-'0')+Output*radix;
else Output=(N[i]-'a'+10)+Output*radix;
if(Output<0) return -1; //溢出返回-1
}
return Output;
}
int main(){
string A[2];
long long tag,radix;
cin>>A[0]>>A[1]>>tag>>radix;
long long num1=0,num2=0;
num1=Convert(A[tag-1],radix);
int min=minRadix(A[2-tag]);
long long left=min,right=(num1>min?num1:min)+1;
long long ans=0;
while(left<=right){
long long mid=(left+right)/2;
num2=Convert(A[2-tag],mid);
if(num2<0||num2>num1) right=mid-1;
else if(num2<num1) left=mid+1;
else{
ans=mid;
break;
}
}
if(ans==0) cout<<"Impossible"<<endl;
else cout<<ans<<endl;
return 0;
}