public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) { // ๆฏๆฌก้ฝ็ๆๅณ้็ๆฏๅฆ็บ1
int count = 0;
for (int i = 0; i < 32; i++) {
count += n & 1;
n = n >> 1;
}
return count;
}
}
optimized
time: O(k), k is the binary length of this num
space: O(1)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count++;
n &= (n-1);
}
return count;
}
}