Offer 15. 二进制中1的个数(hammingWeight)
1. python
class Solution:
def hammingWeight(self, n: int) -> int:
cnt = 0
while n:
cnt = cnt+1
n = n&(n-1)
return cnt
2. Java
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int cnt = 0;
while (n!=0){
cnt+=1;
n=n&(n-1);
}
return cnt;
}
}