Repository: TheAlgorithms/Java
Pull request #5573 (2024-10-05 02:54:07)

countsetbits problem with lookup table approach, runs in O(1) time
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5573?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 54.00%. Comparing base [(`87871ef`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/87871efcdbbcca3a86ac5c2a4e9647b6f8267cf5?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`80a2a90`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/80a2a90a84dc0a219987b09ba7c5a89cbcb9f4c6?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5573      +/-   ##
============================================
+ Coverage     53.96%   54.00%   +0.03%     
- Complexity     3387     3390       +3     
============================================
  Files           535      535              
  Lines         15429    15438       +9     
  Branches       2942     2944       +2     
============================================
+ Hits           8327     8337      +10     
+ Misses         6749     6748       -1     
  Partials        353      353              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5573?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java b/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java
index eb0886e3..242f35fc 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java
@@ -48,4 +48,32 @@ public class CountSetBits {
         }
         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;
+    }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/bitmanipulation/CountSetBitsTest.java b/src/test/java/com/thealgorithms/bitmanipulation/CountSetBitsTest.java
index 41231210..61e0757f 100644
--- a/src/test/java/com/thealgorithms/bitmanipulation/CountSetBitsTest.java
+++ b/src/test/java/com/thealgorithms/bitmanipulation/CountSetBitsTest.java
@@ -14,4 +14,13 @@ public class CountSetBitsTest {
         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));
+    }
 }