Home > Back-end >  How return length of array when using recursion?
How return length of array when using recursion?

Time:09-24

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.

I created this program using recursion and I want to return the length of the array. Do you know how to do it? I would like to keep (If it's possible) the same logic I wrote. Thanks in advance **

def count_bits(n):
    base = n
    count = []
    base = n // 2
    if base:
        if base % 2 ==1:
            count.append(base % 2)
            count  = count_bits(base)
        else:
            count  = count_bits(base)
    return count 

print(count_bits(1234)) # return the array and I want the length
#print(len(count_bits(1234))) # I can not use this method 

CodePudding user response:

Try using a global variable


array_length = 0
def count_bits(n):
    global array_length # global variable
    base = n
    count = []
    base = n // 2
    if base:
        if base % 2 ==1:
            count.append(base % 2)
            array_length =1 # increment when value is 1
            count  = count_bits(base)
        else:
            count  = count_bits(base)
    return count 

count_bits(1234)
print(array_length)

CodePudding user response:

def count_bits(n):
    count = 0
    while n:
        count  = n % 2
        n = n // 2
    return count

Output:

>>> print(count_bits(1234))
5
  • Related