LeetCode每日一题:阶乘后的零
2020-08-05 本文已影响0人
Patarw
- 题目分析,一开始我的想法是把阶乘通过for循环相乘,最后对这个相乘的结果求0的个数,但是运行后发现超出时间限制,所以这是一道看起来简单但实际不太简单的题。
- 所以我们换个角度思考,要判断一个数的尾数有多少个0,是不是可以转化为判断其能够被多少个10整除呢?而10又可以看作是2 * 5,而每隔两位就会有一个偶数,所以2的个数是远远大于5的个数的,所以我们只需要找出5的个数是多少了,下面是代码实现
- 代码:
class Solution {
public int trailingZeroes(int n) {
int index = 0;
for(int i = 1;i <= n;i++){
int m = i;
while(m > 0){
if(m % 5 == 0){
index++;
m = m / 5;
}else{
break;
}
}
}
return index;
}
}
运行过后发现还是超出了时间限制
说明我们的思路还是不够简单,所以看了下官方题解:
- 代码:
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
count += n / 5;
n = n / 5;
}
return count;
}
这道题说是一道算法题,但是我觉得更像是一道数学题