How return length of array when using recursion?

Issue

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 

Solution

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)

Answered By – Shreyas Prakash

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published