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
这道题干啥呢
给两个数,告诉你其中一个数的进制,然后问你另一个数是几进制的时候和另一个相等?
坑点
计算进制转换的数的时候会溢出 - 即使用long long int也不够。我是令溢出的数等于最大值(因为之前的代码不好改),如果从头开始写,可以在转换过程中与目标数比较,如果超过则直接返回过大,而不必完整计算下去。
// 计算整数pow lint pow_int(lint a, lint n) { lint sum = 1; for (int i = 0; i < n; i++) { sum *= a; } return sum; }
// 字符转换为数字 intCharToInt(char c) { if (c >= '0' && c <= '9') return c - '0'; return c - 'a' + 10; }
// 转换为十进制,若溢出,则默认为long long max lint ConvertToDynamic(string number, lint radix) { int len = number.size(); lint sum = 0; for (int i = 0; i < len; i++) { int cur = CharToInt(number[i]); sum += cur * pow_int(radix, len - 1 - i); } if (sum < 0) sum = 9223372036854775807; return sum; }
// 找最大数值 intFindMinRadix(string number) { int max = 0; int len = number.size(); for (int i = 0; i < len; i++) { int cur = CharToInt(number[i]); if (cur > max) max = cur; } return max + 1; }