Modify an array by sorting after reversal of bits of each array element | 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
function binaryToDecimal ( n ) { let num = n ; let dec_value = 0 ; let base = 1 ; let len = num . length ; for ( let i = len - 1 ; i >= 0 ; i -- ) { if ( num [ i ] == ' ' ) dec_value += base ; base = base * 2 ; } return dec_value ; } function decimalToBinary ( n ) { let binstr = " " ; while ( n > 0 ) { binstr += String . fromCharCode ( n % 2 + 48 ) ; n = Math . floor ( n / 2 ) ; } return binstr ; } function reversedBinaryDecimal ( N ) { let decimal_to_binar = decimalToBinary ( N ) ; let binary_to_decimal = binaryToDecimal ( decimal_to_binar ) ; return binary_to_decimal ; } function printSortedArray ( arr , size ) { arr . sort ( function ( a , b ) { return a - b ; } ) ; for ( let i = 0 ; i < size ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( " " ) } function modifyArray ( arr , size ) { for ( let i = 0 ; i < size ; i ++ ) { arr [ i ] = reversedBinaryDecimal ( arr [ i ] ) ; } printSortedArray ( arr , size ) ; } let arr = [ 98 , 43 , 66 , 83 ] ; let n = arr . length ; modifyArray ( arr , n ) ;