Editor

Count the One Bits

#216 · Bit manipulation · Beginner · 30 XP · about 5 min

A program stores a user's permissions in one whole number: each permission is one bit, 1 when it is granted and 0 when it is not. To show how many permissions someone has, you need the number of 1 bits in the binary form of that number.

Write count_ones(n) that returns how many 1s there are in the binary form of the non-negative whole number n.

Try to do it with arithmetic or bit operations (look at the last bit with n & 1, then drop it with n >> 1) rather than by converting the number to a string.

Examples

count_ones(11)    # returns 3
count_ones(0)     # returns 0
count_ones(255)   # returns 8
count_ones(1024)  # returns 1

11 is 1011 in binary, which has three 1s. 1024 is a 1 followed by ten 0s.

Constraints

  • 0 <= n <= 10**18

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.