Closed congr closed 5 years ago
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
// return Integer.bitCount(n);
int cnt = 0;
int mask = 1;
// System.out.println(Integer.toBinaryString(n));
// System.out.println(Integer.toBinaryString(mask));
for (int i = 0; i<32; i++) {
// System.out.println("n & mask = "+ Integer.toBinaryString((n & mask)));
if ((n & mask) != 0) cnt++;
mask <<= 1;
}
return cnt;
}
}
https://leetcode.com/problems/number-of-1-bits/