191. Number of 1 Bits
Solution
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
n = n & (n-1);
count++;
}
return count;
}
ticky的方法: 只能列舉來了解是怎麼運作: n = 3 = 11 n-1 = 2 = 10 可以簡化成 n = (3&2) = 1 , count = 1,的問題
n = 4 = 100 n = 3 = 011 可以簡化成 n = (4&3) = 0 , count = 1,的問題
Last updated
Was this helpful?