172. Factorial Trailing Zeroes

Description

Given an integer n, return the number of trailing zeroes in n!.

Follow up: Could you write a solution that works in logarithmic time complexity?

Example 1:

Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: n = 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Example 3:

Input: n = 0
Output: 0

Constraints:

0 <= n <= 104

Solve

JavaScript solution with short (hard to read🤣) code

Code

1
2
3
4
5
6
7
var trailingZeroes = function (n) {
let c = 0
while (n >= 5) {
c += (n = (n / 5) | 0)
}
return c
}

Explain

As we know, 0 only apear when multiply has 5 and 5‘s multiple, and below every 5‘s multiple, there will always has an even which can multiply 5‘s multiple be a 0 end number.

so I just need find out how many 5‘s multiple exsist in given number N

Last! Also as all we know, 25 is double 5, which can make a two 0 end number, and so on

So, just count how many 5 in N and plus how many 5*5 in N and 5*5*5 in N….

Note: number | 0 is a shot way to get trunc Int number but it requires number less than (2^31)-1