讨论/《图解算法数据结构》 - 剑指 Offer 15 题目解析/
《图解算法数据结构》 - 剑指 Offer 15 题目解析
共 3 个回复
class Solution:
    def hammingWeight(self, n: int) -> int:
        return 0 if n <= 0 else 1 + self.hammingWeight(n & (n - 1))
1
int hammingWeight(uint32_t n) {
    int i;
    int res = 0;
    for(i=0;i<32&&n>0;++i){
        if(n&1==1){
            res++;
        } 
        n >>= 1;
    }
    return res;
}
1
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int cnt = 0;
        for(int i=0; i<32; i++) {
            int t = n & (1 << i);
            if(t != 0) cnt++;
        }
        return cnt;
    }
}
1