题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
dec_num = 0 while 1: try: hex_num = input().lower() if not hex_num: break if '0x' in hex_num: hex_num = hex_num[2:] MSB = len(hex_num) for i in range(MSB): hex_char = hex_num[i] if hex_char == 'f': dec_num += 15 * 16**(MSB - 1 - i) elif hex_char == 'e': dec_num += 14 * 16**(MSB - 1 - i) elif hex_char == 'd': dec_num += 13 * 16**(MSB - 1 - i) elif hex_char == 'c': dec_num += 12 * 16**(MSB - 1 - i) elif hex_char == 'b': dec_num += 11 * 16**(MSB - 1 - i) elif hex_char == 'a': dec_num += 10 * 16**(MSB - 1 - i) else: dec_num += int(hex_char) * 16**(MSB - 1 - i) print(dec_num) except: break
- 穷举法进制转换
- try-except语句用来判定是否接收到了新的输入