Minimum number of given moves required to make N divisible by 25 | C ++ implementation of the approach ; Function to return the minimum number of moves required to make n divisible by 25 ; Convert number into string ; To store required answer ; Length of the string ; To check all possible pairs ; Make a duplicate string ; Number of swaps required to place ith digit in last position ; Number of swaps required to place jth digit in 2 nd last position ; Find first non zero digit ; Place first non zero digit in the first position ; Convert string to number ; If this number is divisible by 25 then cur is one of the possible answer ; If not possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minMoves ( long long n ) { string s = to_string ( n ) ; int ans = INT_MAX ; int len = s . size ( ) ; for ( int i = 0 ; i < len ; ++ i ) { for ( int j = 0 ; j < len ; ++ j ) { if ( i == j ) continue ; string t = s ; int cur = 0 ; for ( int k = i ; k < len - 1 ; ++ k ) { swap ( t [ k ] , t [ k + 1 ] ) ; ++ cur ; } for ( int k = j - ( j > i ) ; k < len - 2 ; ++ k ) { swap ( t [ k ] , t [ k + 1 ] ) ; ++ cur ; } int pos = -1 ; for ( int k = 0 ; k < len ; ++ k ) { if ( t [ k ] != '0' ) { pos = k ; break ; } } for ( int k = pos ; k > 0 ; -- k ) { swap ( t [ k ] , t [ k - 1 ] ) ; ++ cur ; } long long nn = atoll ( t . c_str ( ) ) ; if ( nn % 25 == 0 ) ans = min ( ans , cur ) ; } } if ( ans == INT_MAX ) return -1 ; return ans ; } int main ( ) { long long n = 509201 ; cout << minMoves ( n ) ; return 0 ; }