File tree Expand file tree Collapse file tree 1 file changed +5
-3
lines changed Expand file tree Collapse file tree 1 file changed +5
-3
lines changed Original file line number Diff line number Diff line change 5
5
* @author Nishita Aggarwal
6
6
*
7
7
* Brian Kernighan’s Algorithm
8
+ *
8
9
* algorithm to count the number of set bits in a given number
10
+ *
9
11
* Subtraction of 1 from a number toggles all the bits (from
10
12
* right to left) till the rightmost set bit(including the
11
13
* rightmost set bit).
12
14
* So if we subtract a number by 1 and do bitwise & with
13
- * itself (n & (n-1)), we unset the rightmost set bit.
15
+ * itself i.e. (n & (n-1)), we unset the rightmost set bit.
16
+ *
14
17
* If we do n & (n-1) in a loop and count the no of times loop
15
18
* executes we get the set bit count.
16
- * Number of iterations of the loop is equal to the number of
17
- * set bits in a given integer.
19
+ *
18
20
*
19
21
* Time Complexity: O(logn)
20
22
*
You can’t perform that action at this time.
0 commit comments