Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
public class Solution {
public int trailingZeroes(int n) {
int result=1;
for(int i=1;i<=n;i++){
if ((i%5==0)||(i%10== 0)) result++;
}
return result;
}
}
问题:给你一个整数n。返回n!的尾部的零的个数。
Note:算法的时间复杂度应该是对数级的
分析:
阶乘的结果的最后0的个数,5*一个偶数结尾为0. 10*任意数,结尾为0.
而5一定能遇到足够多的偶数来组成0,
所以就只需要统计1-n中,结尾为5和0的个数。
public class Solution {
public int trailingZeroes(int n) {
int result=1;
for(int i=1;i<=n;i++){
if ((i%5==0)||(i%10== 0)) result++;
}
return result;
}
}
public static int trailingZeroes(int n) {
int count = 0;
while (n / 5 >= 1) {
count += n / 5;
n /= 5;
}
return count;
}