Java:计算java.util.BitSet中设置的位数

时间:2021-09-11 02:59:31

Any quick method to count the number of set bits in a BitSet other than the usual 'keep a counter' method?

除了通常的“保持计数器”方法之外,还有任何快速计算BitSet中设置位数的方法吗?

3 个解决方案

#1


20  

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

cardinality()方法返回设置位数。

#2


3  

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

(假设你不想打电话基数())

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

see javadoc

见javadoc

#3


1  

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

Output:

输出:

1

#1


20  

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

cardinality()方法返回设置位数。

#2


3  

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

(假设你不想打电话基数())

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

see javadoc

见javadoc

#3


1  

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

Output:

输出:

1