简体   繁体   English

Python integer 的所有位的 XOR

[英]Python XOR of all the bits of an integer

I would like to know if an integer's binary representation has an odd number of bits equal to one.我想知道整数的二进制表示是否具有等于 1 的奇数位。

There is a trivial solution by manipulating bytes and using a few shifts but I think that it is more costly than using a XOR of every bits.通过操作字节和使用一些移位有一个简单的解决方案,但我认为它比使用每个位的 XOR 更昂贵。

Is there a way to manipulate bits directly instead of bytes?有没有办法直接操作位而不是字节?

int type is unbounded in python so this could be one way: int 类型在 python 中是无界的,所以这可能是一种方式:

number = 34
i = 0
for n in bin(number):
    if n == '1':
        i += 1
if i % 2 == 0:
    print('even')
else:
    print('odd')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM