text: Maximize the number by flipping at most K bits | 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 [ ] 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
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 maxNum ( 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 cn = 0 NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT if ( a [ i ] == 0 and cn < k ) : NEW_LINE INDENT a [ i ] = 1 NEW_LINE cn = cn + 1 NEW_LINE DEDENT DEDENT return binaryDec ( a , l ) NEW_LINE DEDENT n = 4 NEW_LINE k = 1 NEW_LINE print ( maxNum ( n , k ) ) NEW_LINE