# 172. Factorial Trailing Zeroes

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

C++ 解法一：

``````class Solution {
public:
int trailingZeroes(int n) {
int res = 0;
while (n) {
res += n / 5;
n /= 5;
}
return res;
}
};
``````

Java 解法一：

``````public class Solution {
public int trailingZeroes(int n) {
int res = 0;
while (n > 0) {
res += n / 5;
n /= 5;
}
return res;
}
}
``````

C++ 解法二：

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

Java 解法二：

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

Github 同步地址：

https://github.com/grandyang/leetcode/issues/172

Number of Digit One

https://leetcode.com/problems/factorial-trailing-zeroes/

https://leetcode.com/problems/factorial-trailing-zeroes/discuss/52371/My-one-line-solutions-in-3-languages

https://leetcode.com/problems/factorial-trailing-zeroes/discuss/52373/Simple-CC%2B%2B-Solution-(with-detailed-explaination)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation