PROB1004 进制转换
描述:
将一个十进制数N转换成R进制数输出,2≤R≤16,R≠10。
输入:
多行。第一行指出以下一共有多少组数据,后续每行包含两个整数N和R,以空格分隔,-100000≤N≤100000,2≤R≤16,R≠10。
输出:
多行。每行给出转换后的R进制数。
样例输入:
3 7 2 23 12 -4 3
样例输出:
111 1B -11
基于python实现的代码:
def convert_to_base(N,R):
digits='0123456789ABCDEF'
if N == 0:
return '0'
negative = False
if N<0:
negative = True
N=abs(N)
result =''
while N:
result = digits[N%R] + result
N = N//R
if negative:
result = '-' + result
return result
n = int(input().strip())
for _ in range(n):
N,R = map(int,input().strip().split())
print(convert_to_base(N,R))