1010 Radix (25 point(s))

1010 Radix (25 point(s))

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 N​1​​ and N​2​​, your task is to find the radix of one number while that of the other is given.

Example:

#include<iostream>
#include<cstdlib>

using namespace std;

long trans(char s[], int radix)
{
    long ans = 0;
    while(*s != '\0') {
        int digit;
        ans *= radix;
        if(isdigit(*s)) digit = *s - '0';
        else digit = *s - 'a' + 10;
        if(digit >= radix) {
            ans = 0;
            break;
        }
        ans += digit, s++;
    }
    return ans;
}

void solve(char N1[], char N2[], int radix)
{
    long n = trans(N1, radix);    
    long left = 2;
    long right = max(n, 36L);
    while(left <= right) {
        long var1 = trans(N2, left);
        long var2 = trans(N2, right);
        if(var1 == n) {
            cout << left;
            return;
        } else if(var1 > n) {
            cout << "Impossible";
            return ;
        } else if(var2 == n) {
            if(trans(N2, right-1) < n) {
                cout << right;
                return ;
            }
        }
        left++, right--;
    }
    cout << "Impossible";
}

int main()
{
    char N1[12], N2[12];
    int tag, radix;
    cin >> N1 >> N2 >> tag >> radix;
    if(tag == 1) solve(N1, N2, radix);
    else solve(N2, N1, radix);
}

思路:

从两端匹配,若只从一边匹配则容易超时,另外因为存在1000,10000,100000进制,所以需要自行实现一个进制转换函数,转换成十进制。

需要注意单个数字 digit 不能超过进制 radix。

猜你喜欢

转载自blog.csdn.net/u012571715/article/details/113920879
今日推荐