What is BitSet.previousSetBit() in Java?
previousSetBit() is an instance method of the BitSet class that is used to get the index of the first bit that is set to true on or before the given beginning index. The method returns -1 if no bit is set.
The previousSetBit method is defined in the BitSet class. The BitSet class is defined in the java.util package. To import the BitSet class, use the following import statement.
import java.util.BitSet;
Syntax
public int previousSetBit(int fromIndex)
Parameters
int fromIndex: The starting index.
Return value
This method returns the index of the previous set bit.
Code
import java.util.BitSet;public class Main{public static void main(String[] args) {// Create empty BitSet objectBitSet bitSet = new BitSet();// Set the bit at index 2bitSet.set(2);// Set the bit at index 8bitSet.set(8);int startingIndex = 4;// get the first bit set to true from the startingIndexSystem.out.printf("%s.previousSetBit(%s) = %s", bitSet, startingIndex, bitSet.previousSetBit(startingIndex));}}