text: Invert the Kth most significant bit of N | 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 [ ] into its decimal equivalent ; Function to return the updated integer after flipping the kth bit ; Number of bits in n ; Find the binary representation of n ; The number of bits in n are less than k ; Flip the kth bit ; Return the decimal equivalent of the number ; Driver code
code: function decBinary ( arr , n ) { let k = parseInt ( Math . log2 ( n ) , 10 ) ; while ( n > 0 ) { arr [ k -- ] = n % 2 ; n = parseInt ( n / 2 , 10 ) ; } } function binaryDec ( arr , n ) { let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) ans += arr [ i ] << ( n - i - 1 ) ; return ans ; } function getNum ( n , k ) { let l = parseInt ( Math . log2 ( n ) , 10 ) + 1 ; let a = new Array ( l ) ; a . fill ( 0 ) ; decBinary ( a , n ) ; if ( k > l ) return n ; a [ k - 1 ] = ( a [ k - 1 ] == 0 ) ? 1 : 0 ; return binaryDec ( a , l ) ; } let n = 56 , k = 2 ; document . write ( getNum ( n , k ) ) ;