binary representation 二进制表示
重复把 n 除以 2 ,然后反向读取所有的余数(即:辗转相除法)
while循环实现:编写一个 while 循环完成除以 2 的任务,并顺序输出各二进制
def decimal_to_binary_while_loop(n):
s = ''
while n > 0:
s = str(n%2) + s # 取余后更新 s
n = n//2 # 取整后更新 n
return s
递归实现
def decimal_to_binary_recursion(n, result = ''):
if n == 0: return result # 基例
return decimal_to_binary_recursion(n//2, str(n%2) + result) # 递归链条
'''
递归过程示例
eg: decimal_to_binary_recursion(8, '')
--> n == 8
--> decimal_to_binary_recursion(4, '0') # 8//2, str(8%2) + ''
--> n == 4
--> decimal_to_binary_recursion(2, '00') # 4//2, str(4%2) + '0'
--> n == 2
--> decimal_to_binary_recursion(1, '000') # 8//2, str(2%2) + '00'
--> n == 1
--> decimal_to_binary_recursion(0, '1000') # 1//2, str(1%2) + '000'
--> n == 0
--> return '1000' # result == '1000'
--> return '1000' # decimal_to_binary_recursion(1, '000')
--> return '1000' # decimal_to_binary_recursion(2, '00')
--> return '1000' # decimal_to_binary_recursion(4, '0')
--> return '1000' # decimal_to_binary_recursion(8, '')
'''
代码测试
print(decimal_to_binary_recursion(166)) # >>> 10100110
print(decimal_to_binary_while_loop(167)) # >>> 10100111