Skip to content

Added file to calculate set bits in a number #3262

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions src/main/java/com/thealgorithms/others/countSetBits.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.thealgorithms.others;

public class countSetBits {
/**
* The below algorithm is called as Brian Kernighan's algorithm
* 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.

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.

For example, consider number 52, which is 00110100 in binary, and has a total 3 bits set.

1st iteration of the loop: n = 52

00110100 & (n)
00110011 (n-1)
~~~~~~~~
00110000


2nd iteration of the loop: n = 48

00110000 & (n)
00101111 (n-1)
~~~~~~~~
00100000


3rd iteration of the loop: n = 32

00100000 & (n)
00011111 (n-1)
~~~~~~~~
00000000 (n = 0)

* @param num takes Long number whose number of set bit is to be found
* @return the count of set bits in the binary equivalent
*/
public long countsetBits(long num){
long cnt=0;
while(num>0){
cnt++;
num&=(num-1);
}
return cnt;
}
}
15 changes: 15 additions & 0 deletions src/test/java/com/thealgorithms/others/countSetBitsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.thealgorithms.others;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
public class countSetBitsTest {
@Test
void testSetBits(){
countSetBits csb= new countSetBits();
assertEquals(1L,csb.countsetBits(16));
assertEquals(4, csb.countsetBits(15));
assertEquals(5, csb.countsetBits(10000));
assertEquals(5, csb.countsetBits(31));
}
}