2

I want to write a recursive method function that takes a nonnegative integer n as input and returns the number of 1s in the binary representation on n. I am instructed to use the fact that this is equal to the number of 1s in the representation of n//2 (integer division), plus 1 if n is odd.

    Usage:
    >>> ones(0)
    0
    >>> ones(1)
    1
    >>> ones(14)
    3

ok so this is the code I got so far, it still doesn't work though. it gives me 0 no matter what I input as n.

     def numOnes(n):
     # base case
       if n==0:
          print (0)
       elif n ==1:
          print (1)
     # recursive case
       else:
           return numOnes(n//2)+numOnes(n%2)

Thank you

2
  • 1
    You can just write bin(n).count('1'). Do you know it? There is no reasons to make it recursive. Anyway, you should try something yourself. Commented May 28, 2013 at 14:55
  • If you do integer division by 2, you 'shift' the binary representation of the number to the right by one, losing the right-most bit. For example binary 101 is 5; divide by 2 and binary 10 is 2. Commented May 28, 2013 at 16:26

2 Answers 2

3

These elements you need to do it yourself:

if integer & 1 == 1: # & is the binary and. & 1 will give the lowest bit
    # there is a 1 in the end

integer = integer // 2 # loose one bit in the end
# or
integer = integer >> 1 # loose one bit in the end

Tell me if you need more input.

Your code works for me:

>>> def numOnes(n):
     # base case
       if n==0:
          return (0)
       elif n == 1:
          return (1)
     # recursive case
       else:
           return numOnes(n//2)+numOnes(n%2)


>>> numOnes(0b1100011)
4
Sign up to request clarification or add additional context in comments.

1 Comment

I updated the code a little bit - still not seeing the problem
0

You use print instead of return for the two base cases. Fix that and it'll work:

In [2]: numOnes(15842)
Out[2]: 9

In [3]: bin(15842).count('1')
Out[3]: 9

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.