For a given a positive integer we have to output the complement of its binary representation and output the result in decimal.
Logic is to convert the number in binary , then flip the zeros to ones and ones to zeros and convert the binary to decimal. A simple loop can be used to store the remainders which are flipped in a string , reverse the string and convert to decimal.
First find the nearest integer which is greater than the given number in the power of 2. For example if the given number is 5 (101), the nearest integer would be 8 . If the given number is 8(1000), then the required integer would be 16(10000).This can be done by using the python operator “<<“ in a loop.
while i <= num:
i = i << 1
Now we subtract 1 from 8 so that its binary representation contains exactly the same number of ones (111 binary representation of 7) as the given number(5 in our case).
We can use exclusive OR to flip the digits (111 XOR 101 is 010 ) and return the result
return (i - 1) ^ num