Generate an Array such with elements maximized through swapping bits | C ++ implementation to find maximum sequence by swapping bits ; Function to generate the maximized array elements ; Traverse the array ; Iterate to count set and unset bits ; Count of unset bits ; Count of set bits ; Bitwise right shift ; Shifting all 1 ' s ▁ to ▁ MSB ▁ ▁ and ▁ 0' s to LSB ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximizedArray ( int arr [ ] , int N ) { int num , i = 0 ; while ( N -- ) { num = arr [ i ] ; int one = 0 ; int zero = 0 ; while ( num ) { if ( num % 2 == 0 ) { zero ++ ; } else { one ++ ; } num = num >> 1 ; } for ( int j = zero ; j < ( one + zero ) ; j ++ ) { num += ( 1 << j ) ; } cout << num ; i ++ ; if ( N > 0 ) cout << " , ▁ " ; } } int main ( ) { int arr [ ] = { 8 , 15 , 9 , 10 , 14 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximizedArray ( arr , N ) ; return 0 ; }