Description
Given an integer n, return the number of trailing zeroes in n!.
Example
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Solution
题目要求求出阶乘末尾有多少个0。
首先,末尾有多少个0取决于有多少个10相乘,而10由2×5得到,因此末尾0的个数取决于2与5的组合数。例如,5! = (5 × 4 × 3 × 2 × 1) = (5 × 2 × 2 × 3 × 2 × 1) = 120,因为阶乘中有三个2和一个5,只有一个5×2的组合,所以末尾0的个数也为一个。
又由于阶乘中2的个数总是大于等于5的个数,因此只要计算5的个数就可以了。除此之外,像25这样的数字有5、10、15、20、25,但这其中不止有5个5,25也可以拆成5×5,因此不能单单用n / 5判断出5的个数,还得循环继续判断。
class Solution {
public int trailingZeroes(int n) {
int cnt = 0;
while(n != 0) {
cnt += n / 5;
n /= 5;
}
return cnt;
}
}