http://pat.zju.edu.cn/contests/pat-a-practise/1010
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 10Sample Output 1:
2Sample Input 2:
1 ab 1 2Sample Output 2:
Impossible
有问题的代码:(看了别人的解题报告。。。我觉得这题还是先放着好了=,=)
#include <iostream> #include <cstdio> #include <string> using namespace std; long long f(string s, int radix){ long long x = 0, exp = 1; for (int i = s.size() - 1; i >= 0; i--){ if (s[i] >= '0' && s[i] <= '9'){ x +=(s[i] - '0') * exp; exp *= radix; } else if (s[i] >= 'a' && s[i] <= 'z'){ x += (s[i] - 'a' + 10) * exp; exp *= radix; } } return x; } int main(){ int tag, radix; string s1, s2, s, s0; long long sum; cin >> s1 >> s2 >> tag >> radix; if (tag == 1){ s = s1; s0 = s2; } else if (tag == 2){ s = s2; s0 = s1; } sum = f(s, radix); char max = '0'; int minradix; for (int i = 0; i < s0.size(); ++i){ if (s0[i] > max) max = s0[i]; } if (max <= '9') minradix = max - '0' + 1; else minradix = max - 'a' + 10 + 1; for (int i = minradix; i <= 36; i++){ if (f(s0, i) == sum){ printf("%d\n", i); return 0; } } printf("Impossible\n"); return 0; }