text: Invert the Kth most significant bit of N | C ++ 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 [ ] 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; void decBinary ( int arr [ ] , int n ) { int k = log2 ( n ) ; while ( n > 0 ) { arr [ k -- ] = n % 2 ; n /= 2 ; } } int binaryDec ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += arr [ i ] << ( n - i - 1 ) ; return ans ; } int getNum ( int n , int k ) { int l = log2 ( n ) + 1 ; int a [ l ] = { 0 } ; decBinary ( a , n ) ; if ( k > l ) return n ; a [ k - 1 ] = ( a [ k - 1 ] == 0 ) ? 1 : 0 ; return binaryDec ( a , l ) ; } int main ( ) { int n = 56 , k = 2 ; cout << getNum ( n , k ) ; return 0 ; }