**Solutions**

**Number of 1 Bits** https://leetcode.com/problems/number-of-1-bits/

**Algorithm 1**

- n & (n - 1) drops the** lowest set bit.** It's a neat little bit trick. https://discuss.leetcode.com/topic/20120/c-solution-n-n-1/2

Let's use n = 00101100 as an example. This binary representation has three 1s.

- If n = 00101100, then n - 1 = 00101011, so n & (n - 1) = 00101100 & 00101011 = 00101000. Count = 1.
- If n = 00101000, then n - 1 = 00100111, so n & (n - 1) = 00101000 & 00100111 = 00100000. Count = 2.
- If n = 00100000, then n - 1 = 00011111, so n & (n - 1) = 00100000 & 00011111 = 00000000. Count = 3.
- n is now zero, so the while loop ends, and the final count (the numbers of set bits) is returned.

```
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
cnt = 0
while n:
n, cnt = n & (n-1), cnt + 1
return cnt
```

**Algorithm 2**

- Can we solve this recursively? What is the recurrence here?
- Start with the last bit. If it is odd then it is 1 otherwise it is 0.
- Say we have k bits and N(k) denote the number of bits set to 1.
- Then N(k) = N(k-1) + status_of_last_bit. How do we write this recurrence in terms of number n which can be represented in say k bits?
- F(n) = F(n >> 1) + n % 2
- n%2 can be represented as int(n&1).

```
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
else:
return self.hammingWeight(n>>1) + int(n&1)
```