0

I want to get the number of bits turned on in a BitSet. here is a program to calculate even numbers. Ofcourse, there are easier ways to calculate even numbers, this is just for understanding of how to use BitSets. here is the code:

Public class Test {

public static void main(String[] args) {


        BitSet b = new BitSet();
        for (int i=0; i<10;i++){
            b.set(i);
        }
        System.out.println(b);
        System.out.println("even numbers ");
        int i =0;
        while(i<10){
            if (i%2!=0){
                b.clear(i);
            }
            i++;
        }
        System.out.println(b);
        System.out.println(b.length());
    }
}

output:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
even numbers 
{0, 2, 4, 6, 8}
9

Is there a method to get the number of bits turned on, for example, it should be 5 in the above example. I can always loop through the BitSet and check if (b.set(i)), that would be o(n). Any faster ways to get the count of turned on bits?

Thanks

4

1 回答 1

6

BitSet.cardinality()

返回此 BitSet 中设置为 true 的位数。

http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html#cardinality()

于 2013-11-08T19:42:42.633 回答