PAT 甲级 1010 Radix

https://pintia.cn/problem-sets/994805342720868352/problems/994805507225665536

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

代码:

#include <bits/stdc++.h>
using namespace std;

string N1, N2;
int radix, tag;
long long sum = 0;

long long Pow(long long a, long long b) {
    long long ans1 = 1;

    while(b) {
        if(b % 2) {
            ans1 = ans1 * a;
            b --;
        } else {
            a = a * a;
            b /= 2;
        }
    }
    return ans1;
}

long long num(string s, int system) {
    int ls = s.length();
    reverse(s.begin(), s.end());
    long long ans = 0;
    if(system <= 10) {
        for(int i = 0; i < ls; i ++)
            ans += (s[i] - '0') * Pow(system, i);
    } else {
        int temp;
        for(int i = 0; i < ls; i ++) {
            if(s[i] >= '0' && s[i] <= '9')
                temp = s[i] - '0';
            else temp = s[i] - 'a' + 10;

            ans += temp * Pow(system, i);
        }
    }
    return ans;
}

long long Find(string s, long long res) {
    char it = *max_element(s.begin(), s.end());
    long long l = (isdigit(it) ? it - '0': it - 'a' + 10) + 1;
    long long r = max(res, l);
    long long mid;

    while(l <= r) {
        mid = (l + r) / 2;
        long long rec = num(s, mid);
        if(rec == res) return mid;
        else if(rec > res || rec < 0) r = mid - 1;
        else l = mid + 1;
    }
    return -1;
}

int main() {
    cin >> N1 >> N2 >> tag >> radix;
    int l1 = N1.length(), l2 = N2.length();
    long long out = 0;
    if(tag == 1) {
        sum = num(N1, radix);
        out = Find(N2, sum);
    } else {
        sum = num(N2, radix);
        out = Find(N1, sum);
    } 

    if(out == -1) printf("Impossible
");
    else printf("%lld
", out);
    return 0;
}

  明天就过年啦 希望新年会很多不一样 

FHFHFH

原文地址:https://www.cnblogs.com/zlrrrr/p/10350969.html