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
function minMoves ( n ) { let s = n . toString ( ) ; let ans = Number . MAX_VALUE ; let len = s . length ; for ( let i = 0 ; i < len ; ++ i ) { for ( let j = 0 ; j < len ; ++ j ) { if ( i == j ) continue ; let t = s . split ( ' ' ) ; let cur = 0 ; for ( let k = i ; k < len - 1 ; ++ k ) { swap ( t , k , k + 1 ) ; ++ cur ; } for ( let k = j - ( ( j > i ) ? 1 : 0 ) ; k < len - 2 ; ++ k ) { swap ( t , k , k + 1 ) ; ++ cur ; } let pos = - 1 ; for ( let k = 0 ; k < len ; ++ k ) { if ( t [ k ] != ' ' ) { pos = k ; break ; } } for ( let k = pos ; k > 0 ; -- k ) { swap ( t , k , k - 1 ) ; ++ cur ; } let nn = parseInt ( t . join ( " " ) ) ; if ( nn % 25 == 0 ) ans = Math . min ( ans , cur ) ; } } if ( ans == Number . MAX_VALUE ) return - 1 ; return ans ; } function swap ( t , i , j ) { let temp = t [ i ] ; t [ i ] = t [ j ] ; t [ j ] = temp ; } let n = 509201 ; document . write ( minMoves ( n ) ) ;