【问题标题】:Xor using bitwise operations使用按位运算进行异或
【发布时间】:2021-04-10 00:01:35
【问题描述】:

假设我有一个取两个整数 A,B 的 fn

设A的二进制表示为a0,a1,a2....an,B的二进制表示为b0,b1,b2...bn。

我希望返回这个 ((a0 * b0) ^ (a1 * b1) ^ ..... ^ (an * bn))。

但挑战是在没有位转换的情况下实现这一点,即使用整数。我怎样才能做到这一点?

PS:我知道 A & B 给了我一个数字。当这个数字被转换为二进制并且它的元素相互异或时,我会得到我的答案。但我不希望使用 bin() 将 anded 结果转换为二进制以加快计算速度。

    def find( int A,int B):

      multiply= A & B

      list= bin(multiply)[2:] #(this step I wish to avoid cuz the product can be super large and the binary string is long)

      list = [int(d) for d in list]
    
      innerprod = (reduce(lambda i, j: int(i) ^ int(j), list))

      return innerprod

【问题讨论】:

  • 显示你当前的实现。我不清楚您在做什么,也不清楚您是否了解 ^ 运算符的工作原理。
  • 注明。我添加了我的代码。
  • 这不是python代码...

标签: python-3.x logic bit-manipulation bitwise-operators bit


【解决方案1】:

第一个按位“和”(&) 得到一个数字,其位是输入数字的位,分别相乘。

您可以使用Kernighan's algorithm 来计算设置为 1 的位数(请参阅链接了解说明)。

然后,mod 2 结果,因为 XOR 只是在每次遇到设置为 1 的位时翻转结果(因此,偶数个 1 的 XOR 一起为 0,奇数个将是 1)。

例子:

  • 7 是“111”,5 是“101”
  • 7 & 5 是 '101'(按位“与”运算)
  • '101' 中的两位设置为 1(所以 count_set_bits 返回 2)
  • 2 模 2 为 0。
  • (1 * 1) ^ (1 * 0) ^ (1 * 1) 为 0
def count_set_bits(n):
    count = 0
    while n:
        n &= (n-1)
        count += 1
    return count

def compute_answer(a, b):
    return count_set_bits(a & b) % 2

print(compute_answer(7, 5))   # 0
print(compute_answer(37, 3))  # 1

【讨论】:

  • 非常漂亮。您还可以使用while n:; count += n & 1; n >>= 1 计算位数。不确定哪个更快。另外,python 3.10 会给整数一个内置的bit_length 方法。
  • 感谢 Elinda 理解问题(无需我提供代码)并提供如此出色的答案!太棒了!
  • @MadPhysicist Kernighan 的算法更快。例如,如果输入为 32 ('100000'),则循环只执行一次迭代(计数递增一次)——这是因为 n 中最低有效“1”右侧的所有位都被翻转在 n-1 中——因此,在n & (n-1) 中,那些最右边的位将最终为“0”,而您需要做的就是在没有任何剩余之前计算这种情况发生的次数。这与检查每一位相反,每次移动 1 (n >>= 1)
  • @ELinda。好决定。没想到
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多