Skip to content

countsetbits problem with lookup table approach, runs in O(1) time #5573

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
Oct 6, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,32 @@ public long countSetBits(long num) {
}
return cnt;
}

/**
* This approach takes O(1) running time to count the set bits, but requires a pre-processing.
*
* So, we divide our 32-bit input into 8-bit chunks, with four chunks. We have 8 bits in each chunk.
*
* Then the range is from 0-255 (0 to 2^7).
* So, we may need to count set bits from 0 to 255 in individual chunks.
*
* @param num takes a long number
* @return the count of set bits in the binary equivalent
*/
public int lookupApproach(int num) {
int[] table = new int[256];
table[0] = 0;

for (int i = 1; i < 256; i++) {
table[i] = (i & 1) + table[i >> 1]; // i >> 1 equals to i/2
}

int res = 0;
for (int i = 0; i < 4; i++) {
res += table[num & 0xff];
num >>= 8;
}

return res;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,13 @@ void testSetBits() {
assertEquals(5, csb.countSetBits(10000));
assertEquals(5, csb.countSetBits(31));
}

@Test
void testSetBitsLookupApproach() {
CountSetBits csb = new CountSetBits();
assertEquals(1L, csb.lookupApproach(16));
assertEquals(4, csb.lookupApproach(15));
assertEquals(5, csb.lookupApproach(10000));
assertEquals(5, csb.lookupApproach(31));
}
}