Skip to content

Commit 2cdd97c

Browse files
authored
Improve class & function documentation in HighestSetBit.java (#5577)
1 parent 387707f commit 2cdd97c

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

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

+27-5
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,39 @@
11
package com.thealgorithms.bitmanipulation;
2+
23
import java.util.Optional;
34

45
/**
56
* Find Highest Set Bit
6-
* This class provides a function calculating the position (or index)
7-
* of the most significant bit being set to 1 in a given integer.
8-
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
7+
*
8+
* This class provides a utility method to calculate the position of the highest
9+
* (most significant) bit that is set to 1 in a given non-negative integer.
10+
* It is often used in bit manipulation tasks to find the left-most set bit in binary
11+
* representation of a number.
12+
*
13+
* Example:
14+
* - For input 18 (binary 10010), the highest set bit is at position 4 (zero-based index).
15+
*
16+
* @author Bama Charan Chhandogi
17+
* @version 1.0
18+
* @since 2021-06-23
919
*/
10-
1120
public final class HighestSetBit {
21+
1222
private HighestSetBit() {
1323
}
1424

25+
/**
26+
* Finds the highest (most significant) set bit in the given integer.
27+
* The method returns the position (index) of the highest set bit as an {@link Optional}.
28+
*
29+
* - If the number is 0, no bits are set, and the method returns {@link Optional#empty()}.
30+
* - If the number is negative, the method throws {@link IllegalArgumentException}.
31+
*
32+
* @param num The input integer for which the highest set bit is to be found. It must be non-negative.
33+
* @return An {@link Optional} containing the index of the highest set bit (zero-based).
34+
* Returns {@link Optional#empty()} if the number is 0.
35+
* @throws IllegalArgumentException if the input number is negative.
36+
*/
1537
public static Optional<Integer> findHighestSetBit(int num) {
1638
if (num < 0) {
1739
throw new IllegalArgumentException("Input cannot be negative");
@@ -27,6 +49,6 @@ public static Optional<Integer> findHighestSetBit(int num) {
2749
position++;
2850
}
2951

30-
return Optional.of(position - 1);
52+
return Optional.of(position - 1); // Subtract 1 to convert to zero-based index
3153
}
3254
}

0 commit comments

Comments
 (0)