classSolution(object):defbitwiseComplement(self, N):"""
:type N: int
:rtype: int
"""
n =0
S =0if N ==0:return1while(2**n <= N):if2** n <= N:
S = S +2** n
n = n +1return(N ^ S)# 执行用时 :48 ms, 在所有Python3提交中击败了95.87%的用户# 内存消耗 :13.1 MB, 在所有Python3提交中击败了83.01%的用户
classSolution(object):defbitwiseComplement(self, N):"""
:type N: int
:rtype: int
"""
s =bin(N)[::-1]
k =0for i inrange(len(str(s))-2):if s[i]=='0':
k = k +(2**i)return k
# 执行用时 :68 ms, 在所有Python3提交中击败了33.49%的用户# 内存消耗 :13 MB, 在所有Python3提交中击败了92.28%的用户
算法说明: 首先将N转换为二进制字符串格式,然后翻转;利用for循环判断对应位置的字符是“1”或者“0”,如果是“0”则该位数字在反转之后是“1”,用k = k + (2**i)进行累加计算,输出结果即可。