v9.1.1
Menu

Number of 1 Bits

easyFREEBit ManipulationBlind 75

Given a positive integer, return the number of set bits (1s) in its binary representation (also known as Hamming weight).

Example

Input
11
Output
3
Reasoning
  • The input n is a non-negative integer given in ordinary decimal form, here 1111. The question is about how it is written in base 2, not about its decimal digits.
  • Write 1111 as a sum of distinct powers of two: 11=8+2+1=23+21+2011 = 8 + 2 + 1 = 2^3 + 2^1 + 2^0. The power 22=42^2 = 4 is not needed.
  • Each power that appears becomes a 11 in that position and each missing power becomes a 00, so reading positions 3,2,1,03, 2, 1, 0 gives 101121011_2.
  • The Hamming weight is the number of 11 digits: three of the four positions are set, so the output is 3.
  • Notice that the answer depends only on how many powers of two are used, not on their size: 128=27128 = 2^7 gives 1 even though it is large, while 255=28−1=111111112255 = 2^8 - 1 = 11111111_2 gives 8. An input of 00 uses no powers, so its weight is 00.

Constraints

  • 0 <= n <= 2^31 - 1

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.