Minimum number of given moves required to make N divisible by 25 | 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
< ? php function minMoves ( $ n ) { $ s = strval ( $ n ) ; $ ans = PHP_INT_MAX ; $ len = strlen ( $ s ) ; for ( $ i = 0 ; $ i < $ len ; ++ $ i ) { for ( $ j = 0 ; $ j < $ len ; ++ $ j ) { if ( $ i == $ j ) continue ; $ t = $ s ; $ cur = 0 ; for ( $ k = $ i ; $ k < $ len - 1 ; ++ $ k ) { $ e = $ t [ $ k ] ; $ t [ $ k ] = $ t [ $ k + 1 ] ; $ t [ $ k + 1 ] = $ e ; ++ $ cur ; } for ( $ k = $ j - ( $ j > $ i ) ; $ k < $ len - 2 ; ++ $ k ) { $ e = $ t [ $ k ] ; $ t [ $ k ] = $ t [ $ k + 1 ] ; $ t [ $ k + 1 ] = $ e ; ++ $ cur ; } $ pos = -1 ; for ( $ k = 0 ; $ k < $ len ; ++ $ k ) { if ( $ t [ $ k ] != '0' ) { $ pos = $ k ; break ; } } for ( $ k = $ pos ; $ k > 0 ; -- $ k ) { $ e = $ t [ $ k ] ; $ t [ $ k ] = $ t [ $ k + 1 ] ; $ t [ $ k + 1 ] = $ e ; ++ $ cur ; } $ nn = intval ( $ t ) ; if ( $ nn % 25 == 0 ) $ ans = min ( $ ans , $ cur ) ; } } if ( $ ans == PHP_INT_MAX ) return -1 ; return $ ans ; } $ n = 509201 ; echo minMoves ( $ n ) ; ? >