Skip to content

Commit 8f18b92

Browse files
Add count set bits algorithm (#3262)
1 parent 20a1f40 commit 8f18b92

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.thealgorithms.others;
2+
3+
public class countSetBits {
4+
/**
5+
* The below algorithm is called as Brian Kernighan's algorithm
6+
* We can use Brian Kernighan’s algorithm to improve the above naive algorithm’s performance. The idea is to only consider the set bits of an integer by turning off its rightmost set bit (after counting it), so the next iteration of the loop considers the next rightmost bit.
7+
8+
The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This works as the expression n-1 flips all the bits after the rightmost set bit of n, including the rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n.
9+
10+
For example, consider number 52, which is 00110100 in binary, and has a total 3 bits set.
11+
12+
1st iteration of the loop: n = 52
13+
14+
00110100 & (n)
15+
00110011 (n-1)
16+
~~~~~~~~
17+
00110000
18+
19+
20+
2nd iteration of the loop: n = 48
21+
22+
00110000 & (n)
23+
00101111 (n-1)
24+
~~~~~~~~
25+
00100000
26+
27+
28+
3rd iteration of the loop: n = 32
29+
30+
00100000 & (n)
31+
00011111 (n-1)
32+
~~~~~~~~
33+
00000000 (n = 0)
34+
35+
* @param num takes Long number whose number of set bit is to be found
36+
* @return the count of set bits in the binary equivalent
37+
*/
38+
public long countsetBits(long num){
39+
long cnt=0;
40+
while(num>0){
41+
cnt++;
42+
num&=(num-1);
43+
}
44+
return cnt;
45+
}
46+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.thealgorithms.others;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
public class countSetBitsTest {
7+
@Test
8+
void testSetBits(){
9+
countSetBits csb= new countSetBits();
10+
assertEquals(1L,csb.countsetBits(16));
11+
assertEquals(4, csb.countsetBits(15));
12+
assertEquals(5, csb.countsetBits(10000));
13+
assertEquals(5, csb.countsetBits(31));
14+
}
15+
}

0 commit comments

Comments
 (0)