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.ios
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.git
Each input file contains one test case. Each case occupies a line which contains 4 positive integers:less
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.函數
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.測試
6 110 1 10
2
1 ab 1 2
Impossible
#include <stdio.h> #include <stdlib.h> #include <string> #include <iostream> #include <math.h> #include <algorithm> using namespace std; long long str2num(string s, long long radix){ long long num = 0; for (int i = 0; i < s.length(); i++){ if (s[i] >= '0' && s[i] <= '9')num = num + (s[i] - '0')*pow(radix, s.length() - i - 1); else if (s[i] >= 'a' && s[i] <= 'z')num = num + (s[i] - 'a' + 10)*pow(radix, s.length() - i - 1); } return num; } long long min_radix(string s){ long long max_r = 0; for (int i = 0; i < s.length(); i++){ long long tmp; if (s[i] >= '0' && s[i] <= '9')tmp = s[i] - '0'; else if (s[i] >= 'a' && s[i] <= 'z')tmp = s[i] - 'a' + 10; if (tmp>max_r)max_r = tmp; } return max_r+1; } int main(){ string n1, n2; long long num1 = 0, num2 = 0; long long tag, radix; long long min_r = 0, res = 0, le, ri, mid; cin >> n1 >> n2 >> tag >> radix; if (tag == 1){ num1 = str2num(n1, radix); min_r = min_radix(n2); } else{ num1 = str2num(n2, radix); min_r = min_radix(n1); } le = min_r; ri = max(le,num1); while (le <= ri){ mid = (le + ri) / 2; num2 = str2num(tag==1?n2:n1, mid); if (num2<0 || num2 > num1)ri = mid - 1; else if (num2 < num1)le = mid + 1; else{ res = mid; break; } } if (res != 0)printf("%d", res); else printf("Impossible"); system("pause"); }
注意點:第一:兩個輸入題目保證不超過10位,但沒說幾進制,因此可能會很大,不過好在測試數據都沒有超過long long。this
第二:針對這種兩個換一換的狀況最好寫函數,簡潔明瞭,還能夠直接用swap函數(algorithm頭文件裏)spa
第三:因爲沒有明確上界,須要本身判斷code
第四:範圍太大,逐個遍歷會超時,要用二分法blog
第五:因爲指定數不超過long long,在特定radix下獲得的值溢出long long(小於0),說明太大ci
第六:基數的下限經過遍歷字符串獲得,下限確定比最大的數大1
第七:上界爲ri = max(le,num1);,這裏一直想不通,實際上是這樣的,若是已知數比最小基數要小,用最小基數也仍是可能算出已知數來的,好比已知10進制的8,未知數爲8,9進制就能夠了。