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

2019-02-17 21:47发布

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

标签: java bitset
3条回答
贼婆χ
2楼-- · 2019-02-17 21:52

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

查看更多
聊天终结者
3楼-- · 2019-02-17 22:09

(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

查看更多
萌系小妹纸
4楼-- · 2019-02-17 22:19
BitSet B1 = new BitSet(3);
B1.set(0);
B1.cardinality();

Output:

1
查看更多
登录 后发表回答