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
解:参考了柳神的代码,假如num1是给定的进制,计算出num1的十进制num,解题关键在于找出num2的进制,使其值为num,且进制数取最小的。如果从小到大一个一个试可以取到最小进制,但太暴力,肯定会超时的。
分析进制数递增时的变化,大致可用下图表示(值一开始递增,后面相同)
所以在该题中存在进制的最大最小值,那就可以用二分法找出进制数。
最小值:num2里最大字符+1
最大值:num1的十进制,且比最小值大。如果num2的进制数为radix2,且radix2>=num1,那么肯定有比radix2进制更大的进制,使num1==num2,所以进制最大为num1的值。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String num1 = "";
String num2 = "";
int tag = 1;
long radix = 2;
Scanner scan = new Scanner(System.in);
num1 = scan.next();
num2 = scan.next();
tag = scan.nextInt();
radix = scan.nextLong();
long ans = tag == 1 ? findRadix(num2, convert(num1, radix)) : findRadix(num1, convert(num2, radix));
if (ans != -1) {
System.out.println(ans);
} else {
System.out.println("Impossible");
}
}
static long convert(String n, long radix) {
long sum = 0;
int index = 0, temp = 0;
int i = n.length();
for (char c : n.toCharArray()) {
i--;
temp = c > '9' ? c - 'a' + 10 : c - '0';
sum += temp * Math.pow(radix, i);
}
return sum;
}
static long findRadix(String n, long num) {
char it = '0';
for (char c : n.toCharArray()) {
if (c > it) {
it = c;
}
}
long low = (it > '9' ? it - 'a' + 10 : it - '0') + 1;
long high = num > low ? num : low;
while(low <= high){
long mid = (low + high)/2;
long t = convert(n, mid);
if (t < 0 || t > num) {
high = mid -1;
} else if (t == num) {
return mid;
} else {
low = mid + 1;
}
}
return -1;
}
}