Practice 1010
My Solution
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
typedef long long LL;
using namespace std;
LL toArabicNumeral(char c) {
if(c>= '0' && c<='9') {
return c - '0';
}
return c - 'a' + 10;
}
LL toDecimalNumber(string str, LL radix) {
LL decnum=0;
LL rad=1;
for(int i=str.size()-1; i>=0; i--, rad *= radix) {
decnum += rad * toArabicNumeral(str[i]);
if(decnum < 0 || rad < 0) {
return -1;
}
}
return decnum;
}
int main() {
string N1, N2;
int tag, radix;
cin >> N1 >> N2 >> tag >> radix;
if(tag==2) {
swap(N1, N2);
}
LL decnum = toDecimalNumber(N1, radix);
LL left=2, right=decnum;
for(int i=0; i<N2.size(); i++) {
left = max(left, toArabicNumeral(N2[i]) + 1);
}
LL mid, temp;
while(right >= left) {
mid = (left+right) >> 1;
temp = toDecimalNumber(N2, mid);
if(temp >= decnum || temp == -1) {
right = mid-1;
} else {
left = mid+1;
}
}
if(toDecimalNumber(N2, left) == decnum) {
cout << left << endl;
} else {
cout << "Impossible" << endl;
}
return 0;
}
Test Result
Any idea or discussion is highly welcomed.