Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters | Function to check if all characters of the string can be made the same ; Sort the string ; Calculate ASCII value of the median character ; Stores the minimum number of operations required to make all characters equal ; Traverse the string ; Calculate absolute value of current character and median character ; Print the minimum number of operations required ; Driver Code
function sameChar ( S , N ) { var arr = S . split ( " " ) ; var sorted = arr . sort ( ) ; S = sorted . join ( " " ) ; var mid = S [ parseInt ( N / 2 ) ] . charCodeAt ( 0 ) ; var total_operations = 0 ; for ( var i = 0 ; i < N ; i ++ ) { total_operations += Math . abs ( S [ i ] . charCodeAt ( 0 ) - mid ) ; } document . write ( total_operations ) ; } var S = " " ; var N = S . length ; sameChar ( S , N ) ;