题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
def to_int(i: str) -> int: if i == "A": return 10 if i == "B": return 11 if i == "C": return 12 if i == "D": return 13 if i == "E": return 14 if i == "F": return 15 return int(i) while True: try: num = input() num = num[2:] # get len res = 0 for i in range(0, len(num), 1): res += to_int(num[-1]) * (16 ** i) num = num[:-1] print(res) except: break
很普通正常的思路,更快一点可以把函数 to_int 换成一个字典。类似于这样:
to_16_dict = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, '9': 9, '8': 8, '7': 7, '6': 6, '5': 5, '4': 4, '3': 3, '2': 2, '1': 1, '0': 0, } for i in range(0, len(num), 1): res += to_16_dict[num[-1]] * (16 ** i) num = num[:-1]