irborrero

9/27/2019 - 1:39 AM

```
/*
We have to count the number of 1 an integer n has in its binary representation.
Key concepts:
- When we perform a bitwise operation it is executed in the bit level.
- Withwise operations involved: & and =>> <<== (shift right and shift left)
- 1: 00000000000(..)1
- shift left performed: 000000(...)10
*/
public int hammingWeight(int n) {
//Integer is 32 bits long
int mask = 1;
int count = 0;
for (int i = 0; i < 32; i++) {
if ((n & mask) != 0)
count++;
mask <<= 1;
}
return count;
}
/*
- SECON APPROACH:
- The key concept here is to understand that n&(n-1) converts the least significant 1 bit in n to 0
- 8: n -> 01001000
- 7: n-1 -> 01000111
- Result of AND: 010000000
- So as long as n is not 0 we keep performing this new trick
*/
public int hammingWeight(int n) {
//Integer is 32 bits long
int count = 0;
while (n != 0) {
count++;
n &= (n - 1);
}
return count;
}
```