Maximize the number by flipping at most K bits | 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 maximized number by flipping atmost k bits ; Number of bits in n ; Find the binary representation of n ; To count the number of 0 s flipped ; Return the decimal equivalent of the maximized number ; Driver code
function decBinary ( arr , n ) { let k = Math . log2 ( n ) ; while ( n > 0 ) { arr [ k -- ] = n % 2 ; n = Math . floor ( n / 2 ) ; } } function binaryDec ( arr , n ) { let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) ans += arr [ i ] << ( n - i - 1 ) ; return ans ; } function maxNum ( n , k ) { let l = Math . log2 ( n ) + 1 ; let a = new Array ( l ) . fill ( 0 ) ; decBinary ( a , n ) ; let cn = 0 ; for ( let i = 0 ; i < l ; i ++ ) { if ( a [ i ] == 0 && cn < k ) { a [ i ] = 1 ; cn ++ ; } } return binaryDec ( a , l ) ; } let n = 4 , k = 1 ; document . write ( maxNum ( n , k ) ) ;