class Solution(object):
def findComplement(self, num):
i = 1
while i <= num:
i = i << 1
return (i  1) ^ num
Simple Python

@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


@protein.graph
assume: num = 10101010
if you have tool=11111111
answer = tool ^num
tool = one more bit number 1while i <= num: i = i << 1
this is to get the one more bit number

His website has a great analysis into this algorithm:
http://liqichen.com/dailyleetcode476numbercomplement/

@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
1 line answer:
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)
About 35ms

@protein.graph the origin i = 1 which is 001 in binary code, and suppose num = 5
then i << 1 on every loop,it will be like 0010,0100,1000,which is 2,4,8,then i 1 = 7, which is 0111 in binary,and the ^ calculation means get opposite,when 111^101,you will get 010,which is 2