Minimum number of given moves required to make N divisible by 25 | Python3 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
import sys NEW_LINE def minMoves ( n ) : NEW_LINE INDENT s = str ( n ) ; NEW_LINE ans = sys . maxsize ; NEW_LINE len1 = len ( s ) ; NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT for j in range ( len1 ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT t = s ; NEW_LINE cur = 0 ; NEW_LINE list1 = list ( t ) ; NEW_LINE for k in range ( i , len1 - 1 ) : NEW_LINE INDENT e = list1 [ k ] ; NEW_LINE list1 [ k ] = list1 [ k + 1 ] ; NEW_LINE list1 [ k + 1 ] = e ; NEW_LINE cur += 1 ; NEW_LINE DEDENT t = ' ' . join ( list1 ) ; NEW_LINE list1 = list ( t ) ; NEW_LINE for k in range ( j - ( j > i ) , len1 - 2 ) : NEW_LINE INDENT e = list1 [ k ] ; NEW_LINE list1 [ k ] = list1 [ k + 1 ] ; NEW_LINE list1 [ k + 1 ] = e ; NEW_LINE cur += 1 ; NEW_LINE DEDENT t = ' ' . join ( list1 ) ; NEW_LINE pos = - 1 ; NEW_LINE for k in range ( len1 ) : NEW_LINE INDENT if ( t [ k ] != '0' ) : NEW_LINE INDENT pos = k ; NEW_LINE break ; NEW_LINE DEDENT DEDENT for k in range ( pos , 0 , - 1 ) : NEW_LINE INDENT e = list1 [ k ] ; NEW_LINE list1 [ k ] = list1 [ k + 1 ] ; NEW_LINE list1 [ k + 1 ] = e ; NEW_LINE cur += 1 ; NEW_LINE DEDENT t = ' ' . join ( list1 ) ; NEW_LINE nn = int ( t ) ; NEW_LINE if ( nn % 25 == 0 ) : NEW_LINE INDENT ans = min ( ans , cur ) ; NEW_LINE DEDENT DEDENT DEDENT if ( ans == sys . maxsize ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT n = 509201 ; NEW_LINE print ( minMoves ( n ) ) ; NEW_LINE