1. Topic
Design an algorithm to calculate n factorial of the number of trailing zeros.
示例 1:
输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。
示例 2:
输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/factorial-zeros-lcci
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
2. Problem Solving
- N see how many there are factors of 5
- Source tail 0 is 10, that is 5x an even number, the even better than over five, so you can find the number of 5
- Note also that 25 = 5x5, there are two 5,125 = 5x5x5, there are three 5 .. . .
class Solution {
public:
int trailingZeroes(int n) {
int count = 0;
while(n)
{
count += n/5;
n /= 5;
}
return count;
}
};