给两个数比较能否在特定进制下相等

已经给出一个数的进制

坑点较多

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

实现思想

通过convert()将已经给定进制的数转为10进制

再通过find_radix()将两个数相比较

使用二分法确定另一个数的进制

==数可能较大使用long long类型==

代码实现

#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

long long convert(string n, int r) {
    long long index = 0, sum = 0, temp = 0;
    for(auto it = n.rbegin(); it != n.rend(); it++) {
        temp = isdigit(*it) ? *it - '0' : *it - 'a' + 10;
        sum += temp * pow(r, index++);
    }
    return sum;
}

long long find_radix(string s, long long n) {
    char it = *max_element(s.begin(), s.end());
    long long low = (isdigit(it) ? it - '0' : it - 'a' + 10) + 1;
    long long high = max(n, low);
    long long s_int;
    while(low <= high) {
        long long mid = (high + low) / 2;
        s_int = convert(s, mid);
        if(s_int > n || s_int < 0) {
            high = mid - 1;
        } else if(s_int < n) {
            low = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
}

int main(){
    string n1, n2;
    long long tag, radix, result;
    cin >> n1 >> n2 >> tag >> radix;
    result = tag == 1 ? find_radix(n2, convert(n1, radix)) : find_radix(n1, convert(n2, radix));
    if(result != -1) {
        printf("%d", result);
        return 0;
    }
    printf("Impossible");
    return 0;

}