HJ5 进制转换
描述
写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。
数据范围:保证结果在 1≤n≤2的31次方−1 1≤n≤2的31次方−1
输入描述:
输入一个十六进制的数值字符串。
输出描述:
输出该数值的十进制字符串。不同组的测试用例用\n隔开。
示例1
输入:
0xAA
输出:
170
菜鸡的我是这样写的
import math
data = list(input())
data.pop(0)
data.pop(0)
data.reverse()
total = 0
for i in range(len(data)):
if data[i] == '0' or data[i] == '1' or data[i] == '2' or data[i] == '3' or data[i] == '4' or data[i] == '5' or data[i] == '6' or data[i] == '7' or data[i] == '8' or data[i] == '9':
total += int(data[i]) * math.pow(16,i)
elif data[i] == 'A' or data[i] == 'a':
total += 10 * math.pow(16,i)
elif data[i] == 'B' or data[i] == 'b':
total += 11 * math.pow(16,i)
elif data[i] == 'C' or data[i] == 'c':
total += 12 * math.pow(16,i)
elif data[i] == 'D' or data[i] == 'd':
total += 13 * math.pow(16,i)
elif data[i] == 'E' or data[i] == 'e':
total += 14 * math.pow(16,i)
elif data[i] == 'F' or data[i] == 'f':
total += 15 * math.pow(16,i)
print(int(total))
我看到评论大佬是这样写的(已哭晕 --啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊------------
t = input()
print(int(t,16))
while (True):
try:
t = input()
print(int(t, 16))
except:
break
int函数
强大的自定义进制数转化成十进制。
print(0xA + 0xB) # 21
print(int('0b00110100', 2)) # 52
print(int('00110100', 2)) # 52
print(int('0o144', 8)) # 100
print(int('144', 8)) # 100
print(int('0xC7', 16)) # 199
print(int('C7', 16)) # 199
print(int('33', 17)) # 54