1010 Radix (25)(25 分)(C++)

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

题目大意:给两个数以及其中一个数的进制,判断另一个数有没有可能是这个数不同进制下的形式。

这里采用二分法查找,low为比如eg1中的10最高的数字为1,则它的进制最少为2,high为因为是要与6相等,最进制最大可以取6(即一表示了),这里范围估计得很粗略。

注意点:temp在计算时可能溢出了,所以temp<0的情况一定要注意。

tips:几个比较好用的函数

max_element()  //头文件algorithm;

swap();

isalpha();isdigit();

#include <iostream>
#include <cmath>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
long long convert(string s,long long radix){
    long long sum=0;
    for(int i=0;i<s.size();i++)
        sum=sum*radix+(isdigit(s[i])?(s[i]-'0'):s[i]-'a'+10);
    return sum;
}
int main(){
    string s1,s2;
    int tag;
    long long radix,result=-1;
    cin>>s1>>s2>>tag>>radix;
    if(tag==2)
        swap(s1,s2);
    char it=*max_element(s2.begin(), s2.end());
    long long num1=convert(s1,radix);
    long long low=(isdigit(it)?it-'0':it-'a'+10)+1;
    long long high=max(low,num1);
    while(low<=high){
        long long mid=(low+high)/2;
        long long temp=convert(s2,mid);
        if(temp==num1){
            result=mid;
            break;
        }
        else if(temp<0||num1<temp)
            high=mid-1;
         else 
            low=mid+1;
    }
    if(result==-1)
        printf("Impossible");
    else
        printf("%lld",result);
}

猜你喜欢

转载自blog.csdn.net/qq_41562704/article/details/81979678