Invert the Kth most significant bit of N | Python implementation of the approach ; Function to convert decimal number n to its binary representation stored as an array arr [ ] ; Function to convert the number represented as a binary array arr [ ] its decimal equivalent ; Function to concatenate the binary numbers and return the decimal result ; Number of bits in both the numbers ; Convert the bits in both the gers to the arrays a [ ] and b [ ] ; The number of bits in n are less than k ; Flip the kth bit ; Return the decimal equivalent of the number ; Driver code
import math NEW_LINE def decBinary ( arr , n ) : NEW_LINE INDENT k = int ( math . log2 ( n ) ) NEW_LINE while ( n > 0 ) : NEW_LINE INDENT arr [ k ] = n % 2 NEW_LINE k = k - 1 NEW_LINE n = n // 2 NEW_LINE DEDENT DEDENT def binaryDec ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT ans = ans + ( arr [ i ] << ( n - i - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getNum ( n , k ) : NEW_LINE INDENT l = int ( math . log2 ( n ) ) + 1 NEW_LINE a = [ 0 for i in range ( 0 , l ) ] NEW_LINE decBinary ( a , n ) NEW_LINE if ( k > l ) : NEW_LINE INDENT return n NEW_LINE DEDENT if ( a [ k - 1 ] == 0 ) : NEW_LINE INDENT a [ k - 1 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ k - 1 ] = 0 NEW_LINE DEDENT return binaryDec ( a , l ) NEW_LINE DEDENT n = 56 NEW_LINE k = 2 NEW_LINE print ( getNum ( n , k ) ) NEW_LINE