You are given an integer n, and you must return the number of 1 bits in its binary representation.
This is also known as the Hamming Weight.
-
Convert the number to binary and count all bits that are equal to 1.
-
The input may be large, but bitwise operations make it efficient.
An integer n (32-bit unsigned value).
An integer representing the number of 1 bits in the binary form of n.
Example 1
Input:
n = 11
Binary: 1011
Output:
3
Explanation:
There are three 1s (1 + 1 + 1).
Example 2
Input:
n = 128
Binary: 10000000
Output:
1
Example 3
Input:
n = 0
Binary: 0
Output:
0
-
Input fits in 32-bit unsigned integer.
-
n ≥ 0
-
Use bitwise AND operation: n & 1 checks the last bit.
-
Right shift n until it becomes 0.
-
Or use the trick: n = n & (n - 1) removes the lowest 1-bit.
The simplest approach is to repeatedly check the last bit:
-
Count += n & 1
-
Right shift n (n = n >> 1)
Or use the optimized approach:
-
Every time you do n = n & (n - 1), you remove one 1-bit.
-
Count how many times this operation runs.