Number of 1 Bits
Easy · Bit Manipulation · Bit Manipulation · Divide and Conquer
Problem
Return how many bits are set to 1 in the binary representation of a non-negative integer n — its Hamming weight.
Examples
Input: n = 11 Output: 3
11 is 1011 in binary.
Input: n = 128 Output: 1
128 is 10000000.
Constraints
- 0 <= n <= 2^31 - 1
Approaches
- Shift and test each bit — time O(32), space O(1)
Follow-up
If this function is called many times, how would you optimise it?
Related problems
Start free on Cariara · Coding problems · System design studio