Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

[Python] n & (n-1) trick + even faster, explained 🌟

Using __builtin_popcount

class Solution {
public:
    int hammingWeight(uint32_t n) {
        return (__builtin_popcount(n));
    }
};

Using n=n&(n-1) trick

int hammingWeight(uint32_t n){
    int res = 0;
    while(n){
        n &= n - 1;
        ++ res;
    }
    return res;
}

READ: