java – Palindrome Permutation(破解编码访谈1.4)

我无法理解这两个函数中的位逻辑.

>我不知道为什么我们要检查条件(bitVector& mask)== 0.
>另外,为什么我们在条件满足时将bitVector与掩码进行OR运算,否则将bitVector与〜掩码进行对比?
>为什么有一个属性可以“通过从整数中减去一个并用原始整数与它进行”运算来“检查确切地设置了一个位”?

完整代码here.

/* 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. */
public static boolean checkExactlyOneBitSet(int bitVector) {
    return (bitVector & (bitVector - 1)) == 0;
}

解决方法:

首先,重要的是要理解掩码只有一位设置,所有其他位都为零.如果index为0,则mask为1.如果index为1,则mask为2.如果index为2,则mask为4.如果index为3,则mask为8.如果index为4,则mask为16.依此类推.所有这些掩码值都精确地设置了一位,即索引位.

I don’t know why we are checking for the condition (bitVector & mask) == 0.

如果未设置该位,则该条件为真.如果该位置位,则bitVector&的结果掩码将等于掩码,我们知道掩码不为零.

Also, why do we OR the bitVector with the mask when the condition is satisfied and AND the bitVector with ~mask otherwise?

我们OR值来设置位.我们和〜掩盖以取消位.请记住,掩码只有一位设置,因此〜掩码除了一位设置外都有.

Why is there a property such that one can “check that exactly one bit is set by subtracting one from the integer and ANDing it with the original integer”?

当从数字中减去1时,最后1之后的所有位都变为1.这种情况发生的原因与基数为10的数字以一个或多个零结束时相同,如果减去1,则所有尾随零都变为9.我建议用二进制数来减去一堆数字,减去它后的数值.简单的数学就变得很明显了.

我们来看一个例子,16:

16 : 10000
15 : 01111

很明显,对两个数字进行AND运算将得到0.让我们看另一个例子,48:

48 : 110000
47 : 101111

很明显,使用num-1对一些数字进行AND运算基本上将从最后1位到结束的所有位都清零.如果之前有任何其他位,它们将保留,结果不会为零.如果只有一个1,结果将只为零.

上一篇:Leetcode125. Valid Palindrome


下一篇:如何在Python中生成只有’x’,’y’和给定长度n的回文列表?