Log in

Please Help Improve My Solution To The Binary Count Puzzle

Hello.

I have a solution to the binary count puzzle but I think there are more elegant and efficient solutions available that I hope someone can inform me of.

Within my solution I have avoided using the built-in function bin() and then counting the number of 1's in the string output for two reasons: 1) I don't know how and 2) I am sure there are more elegant mathematical solutions I am missing. I have also created an upperLimit within my code so it can be generalized to scenarios outside the 2^32 bound given.

*Recap of the Mission:
You are given a positive integer as a number, and you need to convert it to the binary format then count how many units (1) there are. For example: 5 = 0b101 contains two units, so the answer is 2.

Input: A number as a positive integer.

Output: The quantity of units in binary form as an integer.*

My Solution:

# number is the input.
# upperLimit is the greatest multiple of 2 that divides into number.
# binCounter counts the occurrences of 1.

def count_units(number):
    upperLimit = 1

    while number / upperLimit >= 1:
        upperLimit = upperLimit * 2

    upperLimit = upperLimit / 2

    binCounter = 0

    while number > 0:

        if number / upperLimit >= 1:
            binCounter = binCounter + 1
            number = number - upperLimit
            upperLimit = upperLimit / 2

        else:
            upperLimit = upperLimit / 2

    return binCounter

Any help and solutions you offer; whether using built-in functions or being mathematically more elegant, is greatly appreciated.
:)
P.s. If this is in the wrong category, please let me know and I'll try to move it.

  • 29 Jul

Hi
try to use bit-shift '>>' or '<<' operators

Reply