简体   繁体   中英

Java: Count number of bits set in a java.util.BitSet

除了通常的“保持计数器”方法以外,还有什么快速的方法可以计算BitSet中设置的位数?

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

(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

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

Output:

1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM