Maximize given integer by swapping pairs of unequal bits | Java implementation of the above approach ; Function to return the maximum possible value that can be obtained from the given integer by performing given operations ; Convert to equivalent binary representation ; Stores binary representation of the maximized value ; Store the count of 0 ' s ▁ and ▁ 1' s ; Stores the total Number of Bits ; If current bit is set ; Increment Count1 ; Increment Count0 ; Shift all set bits to left to maximize the value ; Shift all unset bits to right to maximize the value ; Return the maximized value ; Driver Code ; Given "Input ; Function call to find the Maximum Possible Number
import java . io . * ; class GFG { public static int findMaxNum ( int num ) { String binaryNumber = Integer . toBinaryString ( num ) ; String maxBinaryNumber = " " ; int count0 = 0 , count1 = 0 ; int N = binaryNumber . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( binaryNumber . charAt ( i ) == '1' ) { count1 ++ ; } else { count0 ++ ; } } for ( int i = 0 ; i < count1 ; i ++ ) { maxBinaryNumber += '1' ; } for ( int i = 0 ; i < count0 ; i ++ ) { maxBinaryNumber += '0' ; } return Integer . parseInt ( maxBinaryNumber , 2 ) ; } public static void main ( String [ ] args ) { int N = 11 ; System . out . println ( findMaxNum ( N ) ) ; } }