Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
搞了半天位运算,从小到大都搞不清位运算,专开一章分析吧 最后还是字串弄的
93%
note:replace()函数需要赋值,不是直接在字串上操作
note:二进制字串转十进制利用int()
十进制转二进制字串利用bin() #注意开头是0b
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
string = bin(num)[2:]
string = string.replace('1','a')
string = string.replace('0','1')
string = string.replace('a','0')
return int(string,2)
-------------------------------------
果然,利用亦或运算
比如101,则用111^101,结果为010
问题只剩下构建111,利用左移位运算,最后再减1,最后即可得到所有都为1的二进制数
不过效果没有直接在字串上操作那么好
80.25%
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
i = 1
while i<=num:
i = i<<1
return (i-1)^num
----------------------------------------
或者直接用bit_length()函数 42.58%
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
i = 1
i = i<<(num.bit_length())
return (i-1)^num
----------------------------------------
97.2% 说明还是自己len()函数测量比较高效
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
i = 1
i = i<<(len(bin(num))-2)
return (i-1)^num
--------------------------------------
1.54% 吓一跳 这种把位运算弄成字串转int的写法很耗时
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
i = '1'*len(bin(num)[2:])
return int(i,2)^num
--------------------------------------
format这个函数了不得,这里可以用来进制转换
eg: print "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
结果:'int: 42; hex: 2a; oct: 52; bin: 101010'
print "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
结果:'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
其中o是八进制,x是十六进制,b是二进制,啥符号没有是十进制
68.35%
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
return int(''.join(['1' if i=='0' else '0' for i in '{0:b}'.format(num)]),2)
#for i in '{0:b}'.format(num):
# if i=='0':
# result.append('1')
# else:
# result.append('0')
#num = ''.join(result)
#return int(num,2)