Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to use BitSet with nextSetBit() to find set bits indexes in Java

1 Answer

0 votes
import java.util.BitSet;

public class BitSetDemo {
    public static void main(String[] args) {
        // Create a BitSet with 16 bits
        BitSet bs = new BitSet(16);

        // Set bits at positions 3, 5, 11, and 14
        bs.set(3);
        bs.set(5);
        bs.set(11);
        bs.set(14);

        // Print the BitSet as a binary string
        System.out.println(getBinaryString(bs, 16));

        // Find and print the first set bit
        int firstSetBit = bs.nextSetBit(0);
        System.out.println("First set bit at index: " + firstSetBit);

        // Print all set bit indexes
        System.out.println("All the set bits indexes:");
        for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
            System.out.print(i + " ");
        }
    }

    // Helper method to print BitSet as a binary string
    private static String getBinaryString(BitSet bs, int size) {
        StringBuilder sb = new StringBuilder();
        for (int i = size - 1; i >= 0; i--) {
            sb.append(bs.get(i) ? '1' : '0');
        }
        return sb.toString();
    }
}

 
/*
run:
 
0100100000101000
First set bit at index: 3
All the set bits indexes:
3 5 11 14 
 
*/

 



answered Nov 3, 2025 by avibootz
...