PAT(甲级)1010. Radix (25)

Radix (25)

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

题目大意:给出两个数字串 与 其中一个的进制 若tag==1则给出的为第一个数的进制 tag==2为第二个数的进制 现在求一个进制使两个数字串的值相等
分析:首先想到讲所给进制的数转换为10进制,然后将另一个串转换进制,一直与第一个数比较 相等则输出进制,大于输出Impossible 小于则增加进制再比较 提交24分 一个测试点超时 后来想到进制可能超int很大 遍历增加超时 只能用二分 但是没想到二分的上限 百度一下才明白 还有就是处理溢出问题 之前遍历增加不存在此问题 二分则会有这个问题 因为进制很大很大

#include <iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
char s1[12],s2[12];
long long trans(char s[12],long long r){
    long long n=0;
    int lens=strlen(s);
    for(int i=lens-1;i>=0;i--){
        if(s[i]>'9'){
            n+=pow(r,lens-1-i)*(s[i]-'a'+10);
        }
        else
            n+=pow(r,lens-1-i)*(s[i]-'0');
        if(n<0)//溢出
            return -1;
    }
    return n;
}
int main()
{
    int tag,flag;
    long long n1,n2,rd;
    long long l,r,m;
    scanf("%s%s",s1,s2);
    scanf("%d%lld",&tag,&rd);
    if(tag==1)
        n1=trans(s1,rd);
    else{
        n1=trans(s2,rd);
        memset(s2,'\0',sizeof(s2));
        strcpy(s2,s1);
    }
    l=0;
    int lens=strlen(s2);
    for(int i=0;i<lens;++i){
        if(s2[i]>'9'){
            if(s2[i]-'a'+10>l)
                l=s2[i]-'a'+10;
        }
        else if(s2[i]-'0'>l)
            l=s2[i]-'0';
    }
    l++;//进制下限
    r=n1+1;//进制上限 防止 35 z 1 10 这种数据
    flag=0;
    while(l<=r){
        m=(l+r)/2;
        n2=trans(s2,m);
        if(n2==n1){
            flag=1;
            break;
        }
        else if(n2<0||n2>n1)//溢出肯定是大于n1
            r=m-1;
        else
            l=m+1;
    }
    if(flag)
        printf("%lld",m);
    else
        printf("Impossible");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值