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

Example 1:

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

Example 2:

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

Note: Your solution should be in logarithmic time complexity.

题意:计算一个非负数的阶乘,其尾部有多少个零;

解法一(超时):很自然的想到算计算出这个数的阶乘,再判断其尾部零的个数;但是,即使用long long也存储不下那么大的数字,因此,考虑用数组来存储计算结果;最后时间复杂度也是太高,因此会导致超时;

Java
class Solution {
public int trailingZeroes(int n) {
int[] fac = new int[100000]; //计算阶乘后每一位的数字
fac[0] = 1;
int index = 1; //计算阶乘后的位数
int result = 0; //数字尾部0的个数
for (int i = 2; i <= n; i++) {
int carry = 0;
for (int j = 0; j < index; j++) {
int temp = fac[j] * i + carry;
fac[j] = temp % 10;
carry = temp / 10;
}
while (carry > 0) {
fac[index] = carry % 10;
carry /= 10;
index++;
}
}
for (int i = 0; i < index; i++) {
if (fac[i] == 0) result++;
else break;
}
return result;
}
}

解法二:这道题的目的不在于要求解阶乘,而是判断一个数的末尾包含的零的个数,而会产生0的两个基本元素就是5和2;对于2来说这个元素是足够找到的,因此我们需要计算可以有多少个的5;

Java
class Solution {
public int trailingZeroes(int n) {
return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
}
}