[PYTHON](PAT)1010 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

题目大意

给定两个数字以及其中一个数字的基数,要求找到另外一个数字的基数,使得两个数字相等。

即110在2进制下和6在10进制下是相等的

分析

这道题是除了1029之外通过率最低的一道题目了。

首先我们考虑找到匹配基数的条件:即两个数转换成10进制的值是相等的。

于是首先定义转换函数convert(),用来将任意 基数下的数字转换成十进制下的数字。

之后定义一个find()函数,用于找到合适的基数,使得两个数相等,如果找不到则返回”Impossible”。

注意:

1>直接递增遍历基数是不可能的,因为有些测试点的基数超过10000了,肯定超时,所以采用二分查找法

2>二分查找法要找好上界和下界。因为基数必定比最大的元素大1,所以下界很好找。上界则是在[下界,t(即另一个数在十进制下的值)]中挑最大的

Python实现

def convert(s, radix):

    t = 0

    point = 0

    for x in range(len(s)):

        t += int(s[-x-1], 36) * (radix ** point)

        point += 1

    return t



def find(target,n):

    low = max([ int(x, 36) for x in n]) + 1

    high = max([low, target])

    while(low <= high):

        rad = round((low + high) / 2)

        t= convert(n, rad)

        if t == target:

            return rad

        else:

            if t > target:

                high = rad - 1

            else:

                low = rad + 1

    return 'Impossible'



if __name__ == "__main__":

    line=input().split(" ")

    n1 = line[0]

    n2 = line[1]

    tag = int(line[2])

    radix = int(line[3])

    if tag == 1:

        t = convert(n1, radix)

        print(find(t, n2))

    else:

        t=convert(n2, radix)

        print(find(t, n1))

更多技术干货,有趣文章,点这里就对了

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值