小编Dec*_*mal的帖子

回文排列(破解编码面试1.4)

我在理解这两个函数中的位逻辑时遇到麻烦。

  1. 我不知道为什么我们要检查条件(bitVector&mask)== 0。

  2. 另外,为什么在满足条件时我们将bitVector与掩码进行“或”运算,否则将bitVector与〜mask进行“与”运算呢?

  3. 为什么要有这样一个属性,使得人们可以“通过从整数中减去一位并将其与原始整数进行“与”运算,来检查是否已正确设置了一位?

完整代码在这里

/* Toggle the ith bit in the integer. */
public static int toggle(int bitVector, int index) {
    if (index < 0) return bitVector;

    int mask = 1 << index;
    if ((bitVector & mask) == 0) {
        bitVector |= mask;
    } else {
        bitVector &= ~mask;
    }
    return bitVector;
}

/* Check that exactly one bit is set by subtracting one from the 
 * integer and ANDing it with the original integer. */ …
Run Code Online (Sandbox Code Playgroud)

java bit-manipulation permutation palindrome bitvector

4
推荐指数
1
解决办法
1177
查看次数