Modify an array by sorting after reversal of bits of each array element | C ++ implementation of the above approach ; Function to convert binary number to equivalent decimal ; Set base value to 1 , i . e 2 ^ 0 ; Function to convert a decimal to equivalent binary representation ; Stores the binary representation ; Since ASCII value of '0' , '1' are 48 and 49 ; As the string is already reversed , no further reversal is required ; Function to convert the reversed binary representation to equivalent integer ; Stores reversed binary representation of given decimal ; Stores equivalent decimal value of the binary representation ; Return the resultant integer ; Utility function to print the sorted array ; Sort the array ; Traverse the array ; Print the array elements ; Utility function to reverse the binary representations of all array elements and sort the modified array ; Traverse the array ; Passing array elements to reversedBinaryDecimal function ; Pass the array to the sorted array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binaryToDecimal ( string n ) { string num = n ; int dec_value = 0 ; int base = 1 ; int len = num . length ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( num [ i ] == '1' ) dec_value += base ; base = base * 2 ; } return dec_value ; } string decimalToBinary ( int n ) { string binstr = " " ; while ( n > 0 ) { binstr += ( n % 2 + 48 ) ; n = n / 2 ; } return binstr ; } int reversedBinaryDecimal ( int N ) { string decimal_to_binar = decimalToBinary ( N ) ; int binary_to_decimal = binaryToDecimal ( decimal_to_binar ) ; return binary_to_decimal ; } void printSortedArray ( int arr [ ] , int size ) { sort ( arr , arr + size ) ; for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } void modifyArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { arr [ i ] = reversedBinaryDecimal ( arr [ i ] ) ; } printSortedArray ( arr , size ) ; } int main ( ) { int arr [ ] = { 98 , 43 , 66 , 83 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; modifyArray ( arr , n ) ; return 0 ; }