面试题:二进制与十进制互相转换
面试 Python About 521 words十进制转二进制
方法一:直接调用内置函数bin()
print(bin(123))
方法二:取余 + 地板除
def decimal_to_binary(n):
bin_str = ''
while n:
bin_str = str(n % 2) + bin_str
n //= 2
return bin_str
print(decimal_to_binary(123))
二进制转十进制
方法一:直接调用内置函数int()
print(int('0b1111011', 2))
方法二:2n+2n-1+...+20
def binary_to_decimal(m):
length = len(m)
i = 1
decimal = 0
for c in m:
decimal += int(c) * (2 ** (length - i))
i += 1
return decimal
print(binary_to_decimal('1111011'))
Views: 3,397 · Posted: 2019-10-19
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...