比较常见的思路是把十进制转换成二进制,按位取反后再转换成十进制输出。
class Solution(object):
def bitwiseComplement(self, N):
"""
:type N: int
:rtype: int
"""
# x = 1
# while N > x :
# x = 2 * x + 1
# return x - N
ss = bin(N)[2:]
res = ''
for s in ss:
if s == '0':
res += '1'
else:
res += '0'
return int(res,2)
这里有一个点要注意, python中的转换函数 bin()
bin(30) return `0b11110`
所以要想使用转换后的字符串,就从下标为2开始
ss = bin(N)[2:]
一个新思路:
find the first number X that X = 1111....1 >= N
N + bitwiseComplement(N) = 11....11 = X
Then bitwiseComplement(N) = X - N
但是我们可以换一下思路
1.是N and bitwise(N)加起来的结果每一位都是1,所以先求出1111...1>N(这里求111...1的时候也有一点小技巧,日常思路我们会把1111...1的数表示成 2^n-1,这里我们把它表示成2x+1
2.是 N和2x+1 异或的结果就是bitwise(N)
python代码如下:(因为最近在学深度学习,tensorflow,所以在练习python)
class Solution(object):
def bitwiseComplement(self, N):
"""
:type N: int
:rtype: int
"""
x = 1
while N > x :
x = 2 * x + 1
return x - N