comments | difficulty | edit_url |
---|---|---|
true |
简单 |
设计一个算法,算出 n 阶乘有多少个尾随零。
示例 1:
输入: 3 输出: 0 解释: 3! = 6, 尾数中没有零。
示例 2:
输入: 5 输出: 1 解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。
题目实际上是求
我们以
- 第
次除以 ,得到 ,表示存在 个包含因数 的数; - 第
次除以 ,得到 ,表示存在 个包含因数 的数; - 第
次除以 ,得到 ,表示存在 个包含因数 的数; - 累加得到从
中所有 的因数的个数。
时间复杂度
class Solution:
def trailingZeroes(self, n: int) -> int:
ans = 0
while n:
n //= 5
ans += n
return ans
class Solution {
public int trailingZeroes(int n) {
int ans = 0;
while (n > 0) {
n /= 5;
ans += n;
}
return ans;
}
}
class Solution {
public:
int trailingZeroes(int n) {
int ans = 0;
while (n) {
n /= 5;
ans += n;
}
return ans;
}
};
func trailingZeroes(n int) int {
ans := 0
for n > 0 {
n /= 5
ans += n
}
return ans
}
function trailingZeroes(n: number): number {
let ans = 0;
while (n) {
n = Math.floor(n / 5);
ans += n;
}
return ans;
}
class Solution {
func trailingZeroes(_ n: Int) -> Int {
var count = 0
var number = n
while number > 0 {
number /= 5
count += number
}
return count
}
}