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.
给定一对正整数,例如6和110,这个方程6=110是真的吗?如果6是十进制数,110是二进制数,那么答案是肯定的。
现在对于任意一对正整数N1和N2, 你的任务是找到一个数字的基数,而另一个的基数是给定的。
Input Specification:
Each input file contains one test case. Each case occupies a line which contains 4 positive integers:
每个输入文件包含一个测试用例。每种情况占用一行,该行包含4个正整数:
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.
这里,N1和N2各自具有不超过10个数字。一个数字小于其基数,从集合{0-9,A-z}中选择,其中0-9表示十进制数字0-9,A-z表示十进制数字10-35。如果标记为1,则最后一个数字基数是N1的基数,如果标记为2,则最后的数字基数是N2的基数。
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.
对于每个测试用例,在一行中打印另一个数字的基数,以便公式N1=N2为真。如果方程式不可能,请打印“不可能”。如果解决方案不是唯一的,则输出尽可能小的基数。
Sample Input 1:
6 110 1 10
Sample Output 1:
2
Sample Input 2:
1 ab 1 2
Sample Output 2:
Impossible
思路:这题比较难想到,这道题最关键的是要注意到:不管N1和N2的初始进制是多少,他们最后如果在某个进制上相等了,那他们一起转化成10进制也一定是相等的。
用二分法查找速度很快
代码转载自其他大佬!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
String str[] = rd.readLine().split(" ");
long tag = Long.parseLong(str[2]);
long radix = Long.parseLong(str[3]);
String n1= str[0];
String n2= str[1];
long ans = (tag==1) ? toRadix(toDecimal(radix, n1), n2) : toRadix(toDecimal(radix, n2), n1);
if(ans == -1)
System.out.print("Impossible");
else
System.out.print(ans);
}
//二分法查找进制
public static long toRadix(long dec, String n) {
//这里long类型的变量为什么可以用单引号赋值,我查了久也没查到
long low = '0';
for (int i = 0; i < n.length(); i++) {
if (low < n.charAt(i)) {
low = n.charAt(i);
}
}
low = ((low>='0' && low<='9') ? low - '0' : low - 'a' + 10) + 1;
long high = Math.max(low, dec);
while(high>=low) {
long mid = (low+high) / 2;
long temp = toDecimal(mid,n);
if(temp == dec) return mid;
else if(temp > dec) high = mid - 1;
else low = mid + 1;
}
return -1;
}
//将字符串n转化为十进制
public static long toDecimal(long radix, String n) {
long dec = 0;
for(int i=0; i<n.length(); i++) {
char ch = n.charAt(i);
dec +=
(ch>='0'&&ch<='9') ? Math.pow(radix, n.length()-i-1)*(ch-'0') : Math.pow(radix, n.length()-i-1)*(ch-'a'+10);
}
return dec;
}
}