# Simple Python

• ``````class Solution(object):
def findComplement(self, num):
i = 1
while i <= num:
i = i << 1
return (i - 1) ^ num
``````

• This post is deleted!

• Could you explain the logic behind this?

• @protein.graph after the while loop, i is one bit left than num, if we minus 1, i and num will have the same bit range which can be used to solve our problem

• smart solution.

An very import thing we need to notice is that the condition for while loop is to use "<=" not "<".

• Super simple. Beats my code.

• To make it simpler

``````class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
mask = 1 << (len(bin(num)) - 2)
return (mask - 1) ^ num
``````

• @protein.graph

Example:
5 = 101
shift mask left while shifting a copy of 5 right until it is 0
101 >> 1 == 10
10 >> 1 == 1
1 >> 1 == 0

finally, mask - 1 == 1000 - 1 == 8 - 1 == 111
111 ^ 101
^ sets any of the same bits to 0
result = 010

• ``````   def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
x='1'*(len(bin(num))-2)
return int(x,2)^num``````

• @vishwa123leetcode
the question has asummed no leading zero.

• This is my accepted solution. (i-1) trick was much elegant!

``````class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
b = 0
n = num
while n!=0:
b+=1
n = n>>1
new = 0
while b>0:
b-=1
new = new << 1
new=new|1
return num^new
``````

• @protein.graph
assume: num = 10101010
if you have tool=11111111
tool = one more bit number -1

``````while i <= num:
i = i << 1
``````

this is to get the one more bit number

• I wrote the exact same solution on Java and got TLE. By the way the question assumes "signed integer". This solution fails on all negative inputs.

• His website has a great analysis into this algorithm:
http://liqichen.com/daily-leetcode476-number-complement/

• @sunwhb said in Simple Python:

``````   def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
x='1'*(len(bin(num))-2)
return int(x,2)^num
``````

return int('1'*(len(bin(num))-2),2) ^ num

• My code is similar to yours in ideas.

``````class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
num_v = num
if num == 0:
return 1

count = 1
if num % 2 != 0:
num -= 1

while num > 0:
count += 1
num = num >> 1
if num % 2 != 0:
num -= 1

return num_v ^ (2 ** count - 1)
``````