Right most non | Function to return the rightmost non - zero digit in the multiplication of the array elements ; To store the count of times 5 can divide the array elements ; Divide the array elements by 5 as much as possible ; increase count of 5 ; Divide the array elements by 2 as much as possible ; Decrease count of 5 , because a '2' and a '5' makes a number with last digit '0' ; If c5 is more than the multiplier should be taken as 5 ; Driver code
function rightmostNonZero ( a , n ) { var c5 = 0 ; for ( i = 0 ; i < n ; i ++ ) { while ( a [ i ] > 0 && a [ i ] % 5 == 0 ) { a [ i ] /= 5 ; c5 ++ ; } } for ( i = 0 ; i < n ; i ++ ) { while ( c5 != 0 && a [ i ] > 0 && ( a [ i ] & 1 ) == 0 ) { a [ i ] >>= 1 ; c5 -- ; } } var ans = 1 ; for ( i = 0 ; i < n ; i ++ ) { ans = ( ans * a [ i ] % 10 ) % 10 ; } if ( c5 != 0 ) ans = ( ans * 5 ) % 10 ; if ( ans != 0 ) return ans ; return - 1 ; } var a = [ 7 , 42 , 11 , 64 ] ; var n = a . length ; document . write ( rightmostNonZero ( a , n ) ) ;