PAT1010 Radix
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.
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:
N
1
N1
N1 ,
N
2
N2
N2,
t
a
g
tag
tag ,
r
a
d
i
x
radix
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
解题思路:
二分+防止溢出(数据范围超出
l
o
n
g
long
long
l
o
n
g
long
long)
#include<iostream>
#include<cstdio>
#include<string>
#define ll long long
using namespace std;
int number(char t){
if(t>='0'&&t<='9') return t-'0';
else if(t>='a'&&t<='z') return t-'a'+10;
return -1;
}
ll trans(string s,ll radix){
ll ans=0,temp=1;
for(int i=s.size()-1;i>=0;i--){
ans+=number(s[i])*temp;
temp*=radix;
}
if(ans<0) return -1;//溢出
return ans;
}
int main(int argc, char** argv) {
string s[2];
cin>>s[0]>>s[1];
int tag,radix;
scanf("%d%d",&tag,&radix);
int minv=-1;
int ind=tag-1;//0,1
int ind2=1-ind;
string n1=s[ind],n2=s[ind2];
for(int i=0;i<n2.size();i++){
if(number(n2[i])>minv) minv=number(n2[i]);//rad>=minv+1
}
ll num1=trans(n1,radix);
int flag=0;
ll l=minv+1,r=num1>l?num1:l,mid=-1;//num1溢出时可能为-1
while(l<=r){
mid=(l+r)>>1;
if(trans(n2,mid)>num1||trans(n2,mid)==-1) r=mid-1;//trans(n2,mid)可能溢出
else if(trans(n2,mid)<num1) l=mid+1;
else {
flag=1;break;
}
}
if(!flag) printf("Impossible");
else printf("%lld",mid);
return 0;
}