BitSet previousSetBit(int) in Java

previousSetBit(int): This method is available in java.util.BitSet class of Java.

Syntax:

int java.util.BitSet.previousSetBit(int fromIndex)

This method takes one argument of type int as its parameter. This method returns the index of the nearest bit that is set to true that occurs on or before the specified starting index.

Note: If no such bit exists, or if -1 is given as the starting index, then -1 is returned.

Parameters: One parameter is required for this method.

fromIndex: the index to start checking from (inclusive).

Returns: the index of the previous set bit, or -1 if there is no such bit.

Throws:

IndexOutOfBoundsException - if the specified index is less than -1.

Approach 1: When no exception

Java

import java.util.BitSet;

public class BitSetpreviousSetBit {
    public static void main(String[] args) {
        BitSet bitSet = new BitSet(4);

        bitSet.set(1);

        bitSet.set(5);
        bitSet.set(6);
        bitSet.set(10);

        int fromIndex = 4;
        System.out.println(bitSet.previousSetBit(fromIndex));
    }
}

Output:

1


Approach 2: IndexOutOfBoundsException

Java

import java.util.BitSet;

public class BitSetpreviousSetBit {
    public static void main(String[] args) {
        BitSet bitSet = new BitSet(4);

        bitSet.set(1);

        bitSet.set(5);
        bitSet.set(6);
        bitSet.set(10);

        int fromIndex = -2;
        System.out.println(bitSet.previousSetBit(fromIndex));
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex < -1: -2 at java.base/java.util.BitSet.previousSetBit(BitSet.java:791)


No comments:

Post a Comment