The lockers in use
- O(log n) · Easy
- Free
- Python
- JavaScript
- division
- digits
- loops
Problem
Eufemia looks after the lockers at the swimming club. The board by the door is one of the old ones: instead of lighting a little lamp per locker, it shows a single number. That number, written in binary, says which lockers are in use: every digit 1 is a locker with its key in, and every digit 0 is a free one.
Write a function that takes that number, from 0 up, and returns how many lockers are in use, that is, how many ones the number has when you write it in binary.
With 16 you return 1: in binary 16 is 10000, and it carries a single one. With 89 you return 4, because 89 in binary is 1011001. With 0 you return 0: the board all zeros, no locker in use.
Binary digits come out by dividing by 2 and looking at what is left over: if 1 is left over, that digit is a one and that locker is in use; if 0 is left over, it is free. Then you keep the result of the division and go on, until the number runs out. You do not have to build the binary text: here you only have to count.
Eufemia's board holds up to 31 lockers.
Examples
The one from the example
16 → 1
Eighty-nine
89 → 4
Eight lockers in a row
255 → 8
Two in use and one free
6 → 2
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def taken(n):
passJavaScript
function taken(n) {
}It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.