Minimum number of given moves required to make N divisible by 25 | Java 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
class GFG { static int minMoves ( int n ) { String s = Integer . toString ( n ) ; int ans = Integer . MAX_VALUE ; int len = s . length ( ) ; for ( int i = 0 ; i < len ; ++ i ) { for ( int j = 0 ; j < len ; ++ j ) { if ( i == j ) continue ; char t [ ] = s . toCharArray ( ) ; int cur = 0 ; for ( int k = i ; k < len - 1 ; ++ k ) { swap ( t , k , k + 1 ) ; ++ cur ; } for ( int k = j - ( ( j > i ) ? 1 : 0 ) ; k < len - 2 ; ++ k ) { swap ( t , k , 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 , k - 1 ) ; ++ cur ; } long nn = Integer . parseInt ( String . valueOf ( t ) ) ; if ( nn % 25 == 0 ) ans = Math . min ( ans , cur ) ; } } if ( ans == Integer . MAX_VALUE ) return - 1 ; return ans ; } static void swap ( char t [ ] , int i , int j ) { char temp = t [ i ] ; t [ i ] = t [ j ] ; t [ j ] = temp ; } public static void main ( String [ ] args ) { int n = 509201 ; System . out . println ( minMoves ( n ) ) ; } }