TCS NQT Coding Question-2: toggling all bits

TCS NQT Coding Question-2: toggling all bits

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 -> Integer
Output:
3 -> result- Integer
Explanation:

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).

Leave a Reply

Your email address will not be published. Required fields are marked *

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds