Problem 125525 · easy · Phase 01 Prerequisites & Setup

Ones in Binary

loops · while · binary · modulo

Write count_ones(n) that returns how many 1 bits appear in the binary form of the non-negative integer n. Solve it with a loop and arithmetic (% 2 and // 2) rather than bin().

Examples

Input:  n = 13
Output: 3
Explanation: 13 is 1101 in binary.

Input:  n = 0
Output: 0

Constraints

  • 0 <= n <= 2**60

Goals

  • Break a number down by repeatedly dividing by 2
  • Count the remainders that equal 1
Starting Python…