1
1
package com .thealgorithms .bitmanipulation ;
2
+
2
3
import java .util .Optional ;
3
4
4
5
/**
5
6
* 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
9
19
*/
10
-
11
20
public final class HighestSetBit {
21
+
12
22
private HighestSetBit () {
13
23
}
14
24
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
+ */
15
37
public static Optional <Integer > findHighestSetBit (int num ) {
16
38
if (num < 0 ) {
17
39
throw new IllegalArgumentException ("Input cannot be negative" );
@@ -27,6 +49,6 @@ public static Optional<Integer> findHighestSetBit(int num) {
27
49
position ++;
28
50
}
29
51
30
- return Optional .of (position - 1 );
52
+ return Optional .of (position - 1 ); // Subtract 1 to convert to zero-based index
31
53
}
32
54
}
0 commit comments