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