使用按位运算符/位操作将十进制分解为 2 的幂.因此,如果我们有 9 = 2^0 + 2^3


public static void main(String[] args) {
    System.out.println(bitsSet(14));
}
public static BitSet bitSet(long num) {
    BitSet bitSet = new BitSet();
    for (int i = 0; i < 64; i++) {
        if (((num >>> i) & 1) != 0) {
            bitSet.set(i);
        }
    }
    return bitSet;
}

我在上面尝试了这段代码,但我的 bitSet.set 给出了错误,我不确定我的方法是否正确

方法名称和调用名称不同。

System.out.println(bitsSet(14));

而你的方法有。

public static BitSet bitSet(long num) 
{
...
}

此外,我建议您为变量和函数使用不同的名称。

public static BitSet bitSet(long num) 
{
BitSet myBitSet = new BitSet();
...
}

相关内容

最新更新