(int n)
| 53 | |
| 54 | //Count number of set bits |
| 55 | public static int countSetBits(int n) { |
| 56 | int setBits = 0; |
| 57 | int bitMask = 1; |
| 58 | while(n != 0) { |
| 59 | if((n & bitMask) != 0) { //last bit is 1 |
| 60 | setBits++; |
| 61 | } |
| 62 | n = n>>1; |
| 63 | } |
| 64 | return setBits; |
| 65 | } |
| 66 | |
| 67 | //a faster method to count set bits |
| 68 | public static int countSetBits2(int n) { |