mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-08 02:04:31 +08:00
Improve class & function documentation in HighestSetBit.java
(#5577)
This commit is contained in:
@ -1,17 +1,39 @@
|
|||||||
package com.thealgorithms.bitmanipulation;
|
package com.thealgorithms.bitmanipulation;
|
||||||
|
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Find Highest Set Bit
|
* Find Highest Set Bit
|
||||||
* This class provides a function calculating the position (or index)
|
*
|
||||||
* of the most significant bit being set to 1 in a given integer.
|
* This class provides a utility method to calculate the position of the highest
|
||||||
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
|
* (most significant) bit that is set to 1 in a given non-negative integer.
|
||||||
|
* It is often used in bit manipulation tasks to find the left-most set bit in binary
|
||||||
|
* representation of a number.
|
||||||
|
*
|
||||||
|
* Example:
|
||||||
|
* - For input 18 (binary 10010), the highest set bit is at position 4 (zero-based index).
|
||||||
|
*
|
||||||
|
* @author Bama Charan Chhandogi
|
||||||
|
* @version 1.0
|
||||||
|
* @since 2021-06-23
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public final class HighestSetBit {
|
public final class HighestSetBit {
|
||||||
|
|
||||||
private HighestSetBit() {
|
private HighestSetBit() {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the highest (most significant) set bit in the given integer.
|
||||||
|
* The method returns the position (index) of the highest set bit as an {@link Optional}.
|
||||||
|
*
|
||||||
|
* - If the number is 0, no bits are set, and the method returns {@link Optional#empty()}.
|
||||||
|
* - If the number is negative, the method throws {@link IllegalArgumentException}.
|
||||||
|
*
|
||||||
|
* @param num The input integer for which the highest set bit is to be found. It must be non-negative.
|
||||||
|
* @return An {@link Optional} containing the index of the highest set bit (zero-based).
|
||||||
|
* Returns {@link Optional#empty()} if the number is 0.
|
||||||
|
* @throws IllegalArgumentException if the input number is negative.
|
||||||
|
*/
|
||||||
public static Optional<Integer> findHighestSetBit(int num) {
|
public static Optional<Integer> findHighestSetBit(int num) {
|
||||||
if (num < 0) {
|
if (num < 0) {
|
||||||
throw new IllegalArgumentException("Input cannot be negative");
|
throw new IllegalArgumentException("Input cannot be negative");
|
||||||
@ -27,6 +49,6 @@ public final class HighestSetBit {
|
|||||||
position++;
|
position++;
|
||||||
}
|
}
|
||||||
|
|
||||||
return Optional.of(position - 1);
|
return Optional.of(position - 1); // Subtract 1 to convert to zero-based index
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user