题源
思路
- 刚开始拿到这一题,我先想到的就是10 * 1 = 10;5 * 2 = 10,然后就按这个思路想,但是后面可以把10 * 1 = 5 * 2 * 1 =
5 * 2 = 10
。 - 题目其实就是计算5和2的个数,但是根据题意,很明显2个个数一定比5多,所以
只需要计算5的个数
。 - 该怎么去求呢,其实每一次在
相差5
的区间中,必定有一个5的倍速
的数,所以就可以已5为间隔进行求5的个数的和
。
代码
JavaScript
var trailingZeroes = function(n) {
let count = 0
for(; n >= 5; n = n / 5){
// 因为JavaScript的除法会产生小数,向下取整即可
count += Math.floor(n / 5)
}
return count
};
执行用时:52 ms, 在所有 JavaScript 提交中击败了98.68%的用户
内存消耗:41.3 MB, 在所有 JavaScript 提交中击败了38.52%的用户
python
class Solution:
def __init__(self):
self.count = 0
def trailingZeroes(self, n: int) -> int:
while n >= 5:
n = floor(n / 5) # 除法会产生小数,向下取整即可
self.count += n
return self.count
执行用时:40 ms, 在所有 Python3 提交中击败了59.35%的用户
内存消耗:15 MB, 在所有 Python3 提交中击败了22.74%的用户
java
class Solution {
private int count;
public Solution(){
this.count = 0;
}
public int trailingZeroes(int n) {
while(n >= 5){
n = n / 5;
this.count += n;
}
return this.count;
}
}
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:38.6 MB, 在所有 Java 提交中击败了21.93%的用户
C
int trailingZeroes(int n){
int count = 0;
while(n >= 5){
n = n / 5;
count += n;
}
return count;
}
执行用时:0 ms, 在所有 C 提交中击败了100.00%的用户
内存消耗:5.4 MB, 在所有 C 提交中击败了46.00%的用户