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

后端 未结 3 1163
小鲜肉
小鲜肉 2021-01-11 11:13

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

相关标签:
3条回答
  • 2021-01-11 11:39

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

    0 讨论(0)
  • 2021-01-11 11:42

    (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

    0 讨论(0)
  • 2021-01-11 11:43
    BitSet B1 = new BitSet(3);
    B1.set(0);
    B1.cardinality();
    

    Output:

    1
    
    0 讨论(0)
提交回复
热议问题