[英]Is there a way to calculate the number of digits of an integer in binary with recursion?
所以我想制作这个 function 的版本,但这次使用递归:
def binary_length(natural):
res = 1
while natural >= 2:
res += 1
natural //= 2
return res
我对此的看法是:
def binary_length_recursive(natural):
res = 1
while natural >= 2:
res += 1
natural //= 2
if res%2==0:
return res
else:
return binary_length_recursive(natural)
我看过推荐的文章,但它们对我的情况没有多大帮助。
递归 function 的想法是递归本身就是循环。
你知道0和1有1个数字,你知道数字的rest是用2除来表示的。因此:
>>> def binary_length(n):
... if n <= 1:
... return 1
... return 1 + binary_length(n//2)
...
测试一下:
>>> [(n, binary_length(n)) for n in range(10)]
[(0, 1), (1, 1), (2, 2), (3, 2), (4, 3), (5, 3), (6, 3), (7, 3), (8, 4), (9, 4)]
您需要再次调用 function 号码除以 2。
def binary_length(number):
if number < 2:
return 1
return 1 + binary_length(number // 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.