python 位运算
python 位运算
-
python 位运算是对整数在二进制级别进行的操作
运算符 名称 描述 示例 & 按位与 两位都为1时结果为1 5 & 3 -> 1 | 按位或 两位至少一个为 1 时结果为1 5 | 3 --> 7 ^ 按位异或 两位不同时结果为1 5 ^3 --> 6 ~ 按位取反 每一位取反 ~5 --> -6 << 左移 左移指定位数,右侧补0 5 << 1 --> 10 >> 右移 右移指定位数,左侧补符号位 10 >> 1 --> 5
实用技巧
1.按位与
# 应用:检查奇偶性
n & 1 =0 时为偶数
n & 1 = 1 时为奇数
def is_even(n):
return (n & 1) == 0
print(is_even(10)) # True
print(is_even(7)) # False
2.按位或
# 应用: 设置特定位为1
def set_bit(n, pos):
"""将第pos位设置为1(从0开始计数)"""
return n | (1 << pos)
print(set_bit(5, 1)) # 5=0101 → 0111=7
3.按位异或(^)
3 ^ 3 = 0
3 ^ 0 = 3
a ^ b ^ b = a ^ 0 = a
#应用: 交换两个数(不使用临时变量)日常不推荐
a, b = 5, 3
a = a ^ b
b = a ^ b
a = a ^ b
#日常
a, b = 5, 3
a, b = b, a
# 应用:找出只出现一次的数字, 其他数字都出现两次
def single_number(nums):
result = 0
for num in nums:
result ^= num
return result
print(single_number([4, 1, 2, 1, 2])) # 4
4.按位取反
print(~5) # -6
print(bin(~5)) # '-0b110'
# 注意:Python使用补码表示,~x = -x-1
print(~0) # -1
print(~-1) # 0
5.左移
# 应用: 乘以2的幂次
def multiply_by_power_of_two(n, power):
return n << power
print(multiply_by_power_of_two(5, 3)) # 5 * 8 = 40
6.右移
# 应用:除以2的幂次(向下取整)
def divide_by_power_of_two(n, power):
return n >> power
print(divide_by_power_of_two(10, 2)) # 10 // 4 = 2
7.判断二进制中1 的个数
def count_ones(x):
count = 0
while x:
x = x & (x - 1) # 每次循环清除一个 1
count += 1
return count
# 示例
print(count_ones(12)) # 输出: 2 (因为 12 的二进制是 1100,包含两个 1)
print(count_ones(7)) # 输出: 3 (因为 7 的二进制是 111,包含三个 1)

浙公网安备 33010602011771号