Skip to content

Commit 55b9080

Browse files
committed
Brian Kernighan’s Algorithm added
1 parent 05efd17 commit 55b9080

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Others/BrianKernighanAlgorithm.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import java.util.Scanner;
2+
3+
/**
4+
*
5+
* @author Nishita Aggarwal
6+
*
7+
* Brian Kernighan’s Algorithm
8+
* algorithm to count the number of set bits in a given number
9+
* Subtraction of 1 from a number toggles all the bits (from
10+
* right to left) till the rightmost set bit(including the
11+
* rightmost set bit).
12+
* So if we subtract a number by 1 and do bitwise & with
13+
* itself (n & (n-1)), we unset the rightmost set bit.
14+
* If we do n & (n-1) in a loop and count the no of times loop
15+
* 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.
18+
*
19+
* Time Complexity: O(logn)
20+
*
21+
*/
22+
23+
24+
public class BrianKernighanAlgorithm {
25+
26+
/**
27+
* @param num: number in which we count the set bits
28+
*
29+
* @return int: Number of set bits
30+
* */
31+
static int countSetBits(int num)
32+
{
33+
int cnt = 0;
34+
while(num != 0)
35+
{
36+
num = num & (num-1);
37+
cnt++;
38+
}
39+
return cnt;
40+
}
41+
42+
43+
/**
44+
*
45+
* @param args : command line arguments
46+
*
47+
*/
48+
public static void main(String args[])
49+
{
50+
Scanner sc = new Scanner(System.in);
51+
int num = sc.nextInt();
52+
int setBitCount = countSetBits(num);
53+
System.out.println(setBitCount);
54+
sc.close();
55+
}
56+
}

0 commit comments

Comments
 (0)