Add Highest Set Bit algorithm (#4330)

This commit is contained in:
Bama Charan Chhandogi
2023-09-06 01:49:23 +05:30
committed by GitHub
parent 72247ed85c
commit fc693e8b51
2 changed files with 69 additions and 0 deletions

View File

@ -0,0 +1,32 @@
package com.thealgorithms.bitmanipulation;
import java.util.Optional;
/**
* 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.
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public final class HighestSetBit {
private HighestSetBit() {
}
public final static Optional<Integer> findHighestSetBit(int num) {
if (num < 0) {
throw new IllegalArgumentException("Input cannot be negative");
}
if (num == 0) {
return Optional.empty();
}
int position = 0;
while (num > 0) {
num >>= 1;
position++;
}
return Optional.of(position - 1);
}
}