|
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");
|
18 | 40 | }
|
19 | 41 |
|
20 | 42 | if (num == 0) {
|
21 |
| - return Optional.empty(); |
| 43 | + return Optional.empty(); // No bits are set in 0 |
22 | 44 | }
|
23 | 45 |
|
24 | 46 | int position = 0;
|
| 47 | + |
| 48 | + // Right-shift the number until it becomes zero, counting the number of shifts |
25 | 49 | while (num > 0) {
|
26 | 50 | num >>= 1;
|
27 | 51 | position++;
|
28 | 52 | }
|
29 | 53 |
|
30 |
| - return Optional.of(position - 1); |
| 54 | + return Optional.of(position - 1); // Subtract 1 to convert to zero-based index |
31 | 55 | }
|
32 | 56 | }
|
0 commit comments