0

我必须编写一个简单的方法来接收索引并将该索引处的“位”从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);
}
4

1 回答 1

4

您应该使用BitSet. 如果你想自己做,你可以说:

public void set(int index) { 
    bits |= (1 << index);
}

如果这是家庭作业,并且上面的代码看起来很神奇,那么您真的需要阅读按位运算符。

这段代码可以解释为:

  • 从数字 1 开始,并将其所有位移动index多次。
  • 将'ed 的值设置为与上一步中的值bits相等bits OR
于 2013-01-18T05:38:12.483 回答