Skip to content

Commit 0c838e8

Browse files
committed
fix: correct CountSetBits algorithm logic
1 parent 0906bf4 commit 0c838e8

1 file changed

Lines changed: 17 additions & 17 deletions

File tree

src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* Utility class to count total set bits from 1 to N
55
* A set bit is a bit in binary representation that is 1
66
*
7-
* @author Your GitHub Username
7+
* @author navadeep
88
*/
99
public final class CountSetBits {
1010

@@ -29,28 +29,28 @@ public static int countSetBits(int n) {
2929
return 0;
3030
}
3131

32-
// Find the position of the most significant bit
33-
int powerOf2 = largestPowerOf2(n);
34-
35-
// Count set bits at position powerOf2
36-
int bitsAtMsb = powerOf2 * (1 << (powerOf2 - 1));
37-
38-
// Count remaining set bits from MSB position
39-
int msbRemainder = n - (1 << powerOf2) + 1;
40-
41-
// Recursively count for remaining numbers
42-
int rest = n - (1 << powerOf2);
43-
44-
return bitsAtMsb + msbRemainder + countSetBits(rest);
32+
// Find the largest power of 2 <= n
33+
int x = largestPowerOf2InNumber(n);
34+
35+
// Total bits at position x: x * 2^(x-1)
36+
int bitsAtPositionX = x * (1 << (x - 1));
37+
38+
// Remaining numbers after 2^x
39+
int remainingNumbers = n - (1 << x) + 1;
40+
41+
// Recursively count for the rest
42+
int rest = countSetBits(n - (1 << x));
43+
44+
return bitsAtPositionX + remainingNumbers + rest;
4545
}
4646

4747
/**
48-
* Finds the position of the largest power of 2 less than or equal to n
48+
* Finds the position of the most significant bit in n
4949
*
5050
* @param n the number
51-
* @return position of largest power of 2
51+
* @return position of MSB (0-indexed from right)
5252
*/
53-
private static int largestPowerOf2(int n) {
53+
private static int largestPowerOf2InNumber(int n) {
5454
int position = 0;
5555
while ((1 << position) <= n) {
5656
position++;

0 commit comments

Comments
 (0)