Skip to content

Commit 06d008c

Browse files
authored
Merge pull request neetcode-gh#3316 from prajval-malhotra/0191-number-of-bits-cpp
Update 0191-number-of-bits.cpp
2 parents 94d4ee8 + 3167bf2 commit 06d008c

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

cpp/0191-number-of-1-bits.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,20 @@ class Solution {
2525
return result;
2626
}
2727
};
28+
29+
30+
/* use kernighan's algorithm to only iterate num(set bits) times */
31+
class Solution {
32+
public:
33+
int hammingWeight(uint32_t n) {
34+
unsigned int count = 0;
35+
36+
while(n) {
37+
++count;
38+
// unset rightmost set bit
39+
n = (n & (n - 1));
40+
}
41+
42+
return count;
43+
}
44+
};

0 commit comments

Comments
 (0)