[Python] 位元運算

Bitwise(位元運算)

a & b Bitwise AND
a | b Bitwise OR
a ^ b Bitwise XOR (exclusive OR)
~a Bitwise NOT
a << n Bitwise left shift
a >> n Bitwise right shift

相關例題

Leetcode #  190. Reverse Bits

class Solution:
  def reverseBits(self, n: int) -> int:
    mask, ans = 1, 0
    for i in range(32):
      ans = (ans << 1) + (1 if n & mask != 0 else 0)
      mask <<= 1
    return ans

Leetcode #  191. Number of 1 Bits

class Solution:
  def hammingWeight(self, n: int) -> int:
    mask, bit_n = 1, 0
    for i in range(32):
      if mask & n != 0:
        bit_n += 1
      mask <<= 1
    return bit_n

Last Updated on 2023/08/16 by A1go

目錄
Bitnami