Bit Manipulation
消去二进制中最右侧的那个“1”
二进制中最右侧的那个“1”x & (x - 1) // 消去 x 最后一位的 1,比如 x = 12,那么在二进制下就是 (1100)2
x = 1100
x - 1 = 1011
x & (x - 1) = 1000LintCode: 142. O(1) Check Power of 2
public class Solution {
/**
* @param n: An integer
* @return: True or false
*/
public boolean checkPowerOf2(int n) {
// write your code here
return (n > 0) && ((n & (n - 1)) == 0);
}
}LintCode: 365. Count 1 in Binary
LintCode: 181. Flip Bits
Solution 1
Solution 2
Solution 3
巧用异或XOR运算
异或XOR运算LintCode: 82. Single Number
XOR Operator
XOR OperatorPython collections.Counter()
collections.Counter()将两个数不同的位设置为“1”,其余为“0”
Last updated