Skip to content

Commit b190cb7

Browse files
authored
Add countsetbits problem with lookup table approach (#5573)
1 parent 1feceb7 commit b190cb7

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

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

+28
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,32 @@ public long countSetBits(long num) {
4848
}
4949
return cnt;
5050
}
51+
52+
/**
53+
* This approach takes O(1) running time to count the set bits, but requires a pre-processing.
54+
*
55+
* So, we divide our 32-bit input into 8-bit chunks, with four chunks. We have 8 bits in each chunk.
56+
*
57+
* Then the range is from 0-255 (0 to 2^7).
58+
* So, we may need to count set bits from 0 to 255 in individual chunks.
59+
*
60+
* @param num takes a long number
61+
* @return the count of set bits in the binary equivalent
62+
*/
63+
public int lookupApproach(int num) {
64+
int[] table = new int[256];
65+
table[0] = 0;
66+
67+
for (int i = 1; i < 256; i++) {
68+
table[i] = (i & 1) + table[i >> 1]; // i >> 1 equals to i/2
69+
}
70+
71+
int res = 0;
72+
for (int i = 0; i < 4; i++) {
73+
res += table[num & 0xff];
74+
num >>= 8;
75+
}
76+
77+
return res;
78+
}
5179
}

src/test/java/com/thealgorithms/bitmanipulation/CountSetBitsTest.java

+9
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,13 @@ void testSetBits() {
1414
assertEquals(5, csb.countSetBits(10000));
1515
assertEquals(5, csb.countSetBits(31));
1616
}
17+
18+
@Test
19+
void testSetBitsLookupApproach() {
20+
CountSetBits csb = new CountSetBits();
21+
assertEquals(1L, csb.lookupApproach(16));
22+
assertEquals(4, csb.lookupApproach(15));
23+
assertEquals(5, csb.lookupApproach(10000));
24+
assertEquals(5, csb.lookupApproach(31));
25+
}
1726
}

0 commit comments

Comments
 (0)