Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sameChar ( string S , int N ) { sort ( S . begin ( ) , S . end ( ) ) ; int mid = S [ N / 2 ] ; int total_operations = 0 ; for ( int i = 0 ; i < N ; i ++ ) { total_operations += abs ( int ( S [ i ] ) - mid ) ; } cout << total_operations ; } int main ( ) { string S = " geeks " ; int N = S . size ( ) ; sameChar ( S , N ) ; return 0 ; }