BiruLyu
6/13/2017 - 6:52 PM

172. Factorial Trailing Zeroes(Recursive).java

public class Solution {
    public int trailingZeroes(int n) {
        long base = 5;
        int count = 0;
        while (base <= n) {
            count += (long)n / base;
            base *= 5;
        }
        return count;
    }
}
/*
To avoid the integer overflow as @localvar mentioned below(in case of 'n >=1808548329' ), the expression " i <= INT_MAX/5" is not a good way to prevent overflow, because 5^13 is > INT_MAX/5 and it's valid.

So, if you want to use "multiply", consider define the 'i' as 'long long' type.

Or, take the solution @codingryan mentioned in below answer!

Input:
1808548329
Output:
452137078
Expected:
452137076
*/
public class Solution {
    public int trailingZeroes(int n) {
         return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
    }
}