In this post, we will see the solution of the Python Coding Question which is already asked in the TCS NQT Exam.

**Problem Statement:** Ankit is learning logic design subject which will be for his next semester. He usually tries to solve unit assignment problems before the lecture. Today he got one tricky question. The problem statement is “A positive integer has been given as an input. Convert decimal value to binary representation. Print the positive integer value after toggling all bits”.

**Constrains-**

**1<=N<=100**

**Example:**

Input :12 -> IntegerOutput:3 -> result- IntegerExplanation:Binary representation of 12 is 1100. After toggling the bits(1100), will get 0011 which represents “3”. Hence output will print “3”.

**Solution 1:** using **math – log()** function concept.

# import math library import math # taking input N = int(input()) # calculating the number of bits num_bits = math.floor(math.log2(N)) + 1 # applying xor operation for toggling all the bits result = N ^ ((2 ** num_bits) - 1) print(result)

**Output:**

12 3

Both time and space complexity in the above case is O(1).

**Solution 2:** using **bin()** and **int()** function.

# input N = int(input()) # convert decimal number into binary number binary_num = bin(N)[2:] # empty string string = "" # iterate through all the digits/char of a binary number for digit in binary_num: # string concatenation based on condition if digit == '0' : string += '1' else : string += '0' # convert binary number back into decimal number result = int(string,2) print(result)

12 3

In this case time complexity is O(n), n is number of digits in the binary format and space complexity is O(1).