Skip to content

Commit 6632c18

Browse files
committed
Improve class & function documentation in HighestSetBit.java
1 parent 842ff52 commit 6632c18

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed
Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,56 @@
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");
1840
}
1941

2042
if (num == 0) {
21-
return Optional.empty();
43+
return Optional.empty(); // No bits are set in 0
2244
}
2345

2446
int position = 0;
47+
48+
// Right-shift the number until it becomes zero, counting the number of shifts
2549
while (num > 0) {
2650
num >>= 1;
2751
position++;
2852
}
2953

30-
return Optional.of(position - 1);
54+
return Optional.of(position - 1); // Subtract 1 to convert to zero-based index
3155
}
3256
}

0 commit comments

Comments
 (0)