Given a non-negative integer n, return how many bits are set to 1 in its binary representation — its population count.
Examples
Example 1:
Input: n = 11
Output: 3
Explanation: 1011.
Example 2:
Input: n = 128
Output: 1
Explanation: 10000000.
Example 3:
Input: n = 1
Output: 1
Example 4:
Input: n = 2147483647
Output: 31
Constraints
0 <= n <= 2^31 - 1
Prerequisites
Binary and two's complement — how a negative number is stored, and what a shift does at the edges. The trick worth memorising: n & (n-1) clears the lowest set bit.
How to think about it
1. Clear the Lowest Set Bit Optimal
Intuition
Subtract one from n and its lowest set bit turns to 0, every 0 below that bit turns to 1, and every bit above it stays as it was. So n & (n - 1) keeps the bits above, where n and n - 1 agree, and clears the rest: the lowest set bit is gone, and nothing else changed. Each clear takes away exactly one set bit, so the number of clears before n reaches 0 is the number of set bits, and the zeros are never visited: 128, 10000000, takes one clear, where testing the last bit and shifting right takes eight steps. Check n before each clear, so that n = 0 counts none. Clear the lowest set bit until no bits are set, and count the clears.
Algorithm
1. Start the count at 0. 2. While n is not 0, set n to n & (n - 1), which clears its lowest set bit, and add one to the count. 3. Return the count.
Time & Space
Time O(k), k = the number of set bits. Space O(1).
2. Test the Last Bit, Then Shift
Intuition
Every bit of n reaches the last place in turn if n is shifted right one step at a time. n & 1 is that last bit: 1 when it is set, 0 when it is not, so adding it to the count counts the set bits as they pass. Shifting right drops the bit just tested and brings the next one down. The loop stops when n is 0, so n = 0 counts none, and nothing above the highest set bit is visited. Every 0 below it is: 128, 10000000, takes eight steps to reach its one set bit, where clearing the lowest set bit takes one. In Java, >>> shifts in a 0 from the left, so the loop ends for any int; Learn's n is never negative. Test the last bit, add it to the count, and shift right, until n is 0.
Algorithm
1. Start the count at 0. 2. While n is not 0, add n & 1, its last bit, to the count, and shift n right by one. 3. Return the count.
Time & Space
Time O(log n): one step for every bit up to the highest set one, at most 31. Space O(1).