Find the maximum difference after applying the given operations two times on a number | C ++ program to find the maximum difference after two given operations on a number ; Function that returns the maximum difference after two given operations on a number ; Initialize the strings to make operations ; Store length of the string ; Make the maximum number using the first operation ; Find the first digit which is not equal to '9' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '9' ; Break after the operation is completed ; Check if first digit is equal to '1' ; Find the first digit which is greater than '1' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '0' ; Break after the operation is completed ; Select the first digit for the given operation ; Replace all the selected ' digit ' with '1' ; Return the difference after converting into integers ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDifference ( int num ) { string maximum = to_string ( num ) ; string minimum = to_string ( num ) ; int n = maximum . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( maximum [ i ] != '9' ) { char digit = maximum [ i ] ; for ( int j = i ; j < n ; j ++ ) { if ( maximum [ j ] == digit ) maximum [ j ] = '9' ; } break ; } } if ( minimum [ 0 ] == '1' ) { for ( int i = 1 ; i < n ; i ++ ) { if ( minimum [ i ] - '0' > 1 ) { char digit = minimum [ i ] ; for ( int j = i ; j < n ; j ++ ) { if ( digit == minimum [ j ] ) minimum [ j ] = '0' ; } break ; } } } else { char digit = minimum [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( minimum [ i ] == digit ) minimum [ i ] = '1' ; } } return ( stoi ( maximum ) - stoi ( minimum ) ) ; } int main ( ) { int N = 1101157 ; cout << minDifference ( N ) ; return 0 ; }