与 & AND
运算规则
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
Example
Calculate 3 & 5:
3: 0011
5: 0101
3&5: 0001
负数
负数按补码参与按位与运算。
或 | OR
运算规则
0 | 0 = 0
0 | 1 = 1
1 | 0 = 0
1 | 1 = 1
Example
Calculate 3 | 5:
3: 0011
5: 0101
3|5: 0111
异或 ^ XOR
运算规则
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 0
1 ^ 1 = 0
Example
Calculate 3 ^ 5:
3: 0011
5: 0101
3^5: 0110
取反 ~ NOT
运算规则
~ 0 = 1
~ 1 = 0
左移 <<,右移 >>
运算规则
按二进制左/右移 N位
Example
1 << 3
1 | 0001 << 3 |
10 >> 2
1 | 1010 >> 2 |
EX: Leetcode371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator
+
and-
.Example:
Given a = 1 and b = 2, return 3.
1 | class Solution: |
1 | # 用mask解决负数问题 |