Skip to content

Commit fa26245

Browse files
committed
Add Count Total Set Bits from 1 to N (Bit Manipulation)
1 parent fd840dd commit fa26245

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* Count the total number of set bits in binary representations of all numbers from 1 to N.
5+
*
6+
* <p>This implementation uses bit manipulation and mathematical observation to
7+
* efficiently calculate the total number of set bits in O(log N) time.
8+
*
9+
* <p>Example:
10+
* N = 3 -> Binary(1):01, Binary(2):10, Binary(3):11 => Total Set Bits = 4
11+
*
12+
* <p>Reference: https://www.geeksforgeeks.org/count-total-set-bits-in-all-numbers-from-1-to-n/
13+
*/
14+
public final class CountTotalSetBits {
15+
16+
private CountTotalSetBits() {
17+
// utility class
18+
}
19+
20+
/**
21+
* Returns the total count of set bits in binary representations of all numbers from 1 to n.
22+
*
23+
* @param n the upper limit of the range
24+
* @return total number of set bits from 1 to n
25+
*/
26+
public static int countTotalSetBits(int n) {
27+
if (n == 0) {
28+
return 0;
29+
}
30+
31+
int x = largestPowerOf2(n);
32+
int bitsTill2x = x * (1 << (x - 1));
33+
int msbBits = n - (1 << x) + 1;
34+
int rest = n - (1 << x);
35+
36+
return bitsTill2x + msbBits + countTotalSetBits(rest);
37+
}
38+
39+
/**
40+
* Helper function to find the largest power of 2 less than or equal to n.
41+
*/
42+
private static int largestPowerOf2(int n) {
43+
int x = 0;
44+
while ((1 << x) <= n) {
45+
x++;
46+
}
47+
return x - 1;
48+
}
49+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import org.junit.jupiter.api.Test;
5+
6+
/**
7+
* Test cases for {@link CountTotalSetBits}.
8+
*/
9+
public class CountTotalSetBitsTest {
10+
11+
@Test
12+
void testSmallNumbers() {
13+
assertEquals(4, CountTotalSetBits.countTotalSetBits(3)); // 1->1,2->1,3->2
14+
assertEquals(5, CountTotalSetBits.countTotalSetBits(4)); // 1,2,3,4 -> total 5
15+
}
16+
17+
@Test
18+
void testPowerOfTwo() {
19+
assertEquals(12, CountTotalSetBits.countTotalSetBits(7)); // from 1 to 7
20+
}
21+
22+
@Test
23+
void testLargerNumber() {
24+
assertEquals(17, CountTotalSetBits.countTotalSetBits(10)); // verified manually
25+
}
26+
27+
@Test
28+
void testZero() {
29+
assertEquals(0, CountTotalSetBits.countTotalSetBits(0));
30+
}
31+
}

0 commit comments

Comments
 (0)