0

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 
3
  • Why do you need a list for that? (Let alone the recursion, assuming that it's a part of an exercise.) Commented Sep 23, 2021 at 12:30
  • Why it should return 5?? Commented Sep 23, 2021 at 12:30
  • Hi, because there are 5 ones in 10011010010 Commented Sep 23, 2021 at 12:32

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Output:

>>> print(count_bits(1234))
5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.