我必须编写一个简单的方法,它接收索引并将该索引的“位”从0
切换到1
。我在为此编写按位运算符时遇到问题。我知道这很简单但我无法得到它。以下是该方法的样子。提前谢谢!
/**
* 32-bit data initialized to all zeros. Here is what you will be using to represent
* the Bit Vector.
*/
private int bits;
/** You may not add any more fields to this class other than the given one. */
/**
* Sets the bit (sets to 1) pointed to by index.
* @param index index of which bit to set.
* 0 for the least significant bit (right most bit).
* 31 for the most significant bit.
*/
public void set(int index)
{
//It is here where I can not figure it out. Thank you!
System.out.println(~bits);
System.out.println("setting bit: " + bits + " to: " + index);
}
答案 0 :(得分:4)
您应该使用BitSet
。如果你想自己做,你可以说:
public void set(int index) {
bits |= (1 << index);
}
如果这是作业,上面的代码看起来很神奇,你真的需要阅读按位运算符。
此代码可以解释为:
index
次。bits
的值设置为等于bits
OR
'ed的值,并使用上一步中的值