Java: number of bit bits set in java.util.BitSet

Any quick way to count the number of bits in a bitNetwork other than the usual method of "keeping a counter"?

+4
source share
3 answers

The cardinality () method returns the number of bits set.

+20
source

(Assuming you don't want to call power ())

int count = 0; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { count++; } 

see javadoc

+3
source
 BitSet B1 = new BitSet(3); B1.set(0); B1.cardinality(); 

Output:

 1 
0
source

Source: https://habr.com/ru/post/1338209/


All Articles