class Solution(object):
def findComplement(self, num):
temp = 1<<(len(bin(num))-2)
#因为有0b,所以长度减二
temp = temp - 1
num = num ^ temp
return num
num.bit_length()
bit_length:不包含0b两个字段
比如101的反码,1<<3,二进制即1000,减去1,即为0111,同101做异或,返回的就是010
逐位取反
class Solution(object):
def findComplement(self, num):
i = 1
while num >= i:
num ^= i
i <<= 1
return num
1 << 2,可以这么理解,不断的将bit中的1左移,001->010(变成2倍)->100(再变成2倍)