PTA exercises-python 7-7 base conversion

Convert the decimal integer n (−231≤n≤231−1) to base k (2≤k≤16). Note that 10~15 are represented by the letters A, B, C, D, E, and F respectively.

Input format:

First enter a positive integer T, which represents the number of groups of test data, and then T groups of test data. Input two integers n and k for each set of test data.

Output format:

For each group of tests, first output n, then output a space, and finally output the corresponding k-ary number.

Input sample:

4
5 3
123 16
0 5
-12 2

Sample output:

5 12
123 7B
0 0
-12 -1100

analyze

The rule for converting decimal to k (2≤k≤16) base: keep dividing the number by k until the quotient is 0, and then invert the remainder obtained at each step, which is the corresponding k base result.

Note that if the remainder is 10~15, use letters A, B, C, D, E, F to represent

Code 

def f(n,k):
    s = ''
    ss = ''
    while n != 0:
        if n%k in d:
            s = s + d[n%k]
        else:
            s = s + str(n%k)
        n = n // k
    # 把转换后的k进制结果倒过来,才是最终的
    for i in s[::-1]:
        ss += i
    return ss

t = int(input())
for i in range(t):
    n, k = map(int, input().split())
    # 10-15分别用字母A、B、C、D、E、F表示。
    d = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'} 
    if n==0: # 特殊情况
        print('0 0')
    elif n<0: 
        print(n,end=' ')
        print('-'+f(-n,k))
    else :
        print(n,end=' ')
        print(f(n,k))

Submit results

 

Guess you like

Origin blog.csdn.net/weixin_58707437/article/details/128082096