Number of 1 Bits

Tries & Bit Manipulation, problem 2 of 8

Number of 1 Bits

Easy

LC #191

bit manipulation

Not attempted yet

Given a non-negative integer n, return how many 1 bits its binary representation has (its "Hamming weight").

Example 1

Input: n = 11
Output: 3

11 is 1011 in binary.

Example 2

Input: n = 128
Output: 1

128 is 10000000.

Example 3

Input: n = 2147483645
Output: 30

That's 31 bits, all 1 except one.

Constraints

  • 0 ≤ n ≤ 2³¹ - 1

Try it without bin(n).count("1") first.

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 5 hidden

Run examples, then submit all tests.