1010 Radix

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

题目大意:给定两个数,和其中一个数的进制,要求求另一个数的进制,使两个数相等——转换为同一进制。

分析:数字应该用string类型表示,要通过string和进制radix求十进制表示的数。然后求另一数的进制,进制有可能是多少呢?最小进制容易求得。最大进制能多大呢?注意不止是36,还可能很大。因此要应用二分查找方法,而且如果得到负数,则说明进制很大。

参考代码:
需要注意的地方已用注释标注!

#include<iostream>
#include<string>
#include<cmath>
#include<cctype>
#include<algorithm>
using namespace std;

long long int convert(const string &s,long long int radix)
{
    long long int num = 0, temp = 0, jinzhi = 1;
    for (auto it = s.crbegin(); it != s.crend(); it++)
    {
        temp = isdigit(*it) ? *it - '0' : *it - 'a' + 10;
        num = num + temp * jinzhi;
        jinzhi *= radix;
    }
    return num;
}
long long int find_radix(const string &s, long long int num)
{
    char ch = *max_element(s.begin(), s.end());
    long long int left =( isdigit(ch) ? ch - '0' : ch - 'a' + 10)+1;
    long long int right = max(left, num), mid;     //注意right的取值
    while (left <= right)
    {
        mid = (left + right) / 2;         
        long long int temp = convert(s, mid);
      if (temp<0|| temp>num)right = mid - 1;      //注意此处的判断条件
        else if (temp == num)return mid;
        else if(temp<num)left = mid + 1;
    }
    return -1;
}

int main()
{
    string s1,s2;
    int tag, radix;
    long long int  num1, num2, result;
    cin >> s1 >> s2 >> tag >> radix;
    result = tag == 1 ? find_radix(s2, convert(s1, radix)) : find_radix(s1, convert(s2, radix));
    if (result == -1)
        cout << "Impossible";
    else cout << result;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/ssf_cxdm/article/details/81431888