diff --git a/cpp/0191-number-of-1-bits.cpp b/cpp/0191-number-of-1-bits.cpp index 9d91bf039..146c3d990 100644 --- a/cpp/0191-number-of-1-bits.cpp +++ b/cpp/0191-number-of-1-bits.cpp @@ -25,3 +25,20 @@ class Solution { return result; } }; + + +/* use kernighan's algorithm to only iterate num(set bits) times */ +class Solution { +public: + int hammingWeight(uint32_t n) { + unsigned int count = 0; + + while(n) { + ++count; + // unset rightmost set bit + n = (n & (n - 1)); + } + + return count; + } +}; \ No newline at end of file