题目
Given an integer n, return the number of trailing zeroes in n!.
我的解法(超时)
public class Solution {
public int twoNum = 0;
public int fiveNum = 0;
public int trailingZeroes(int n) {
if(n == 0)
return 0;
while(n >= 1){
calcFactor(n);
n --;
}
return Math.min(twoNum, fiveNum);
}
public void calcFactor(int n){
while(n%2 == 0 || n%5 == 0){
if(n%2 == 0){
twoNum ++;
n = n/2;
}
if(n%5 == 0){
fiveNum ++;
n = n/5;
}
}
}
}
答案解法(发现数字的规律)(还需写下完整的算法分析)
public class Solution {
public int trailingZeroes(int n) {
int res = 0;
int i = 1;
while(n >= Math.pow(5, i)){
res += n / Math.pow(5, i);
i ++;
}
return res;
}
}
算法分析:发现数字的规律。0只可能通过2*5的到,而2的个数肯定大于5,所以只要计算5的个数即可。有的数字可以拆成一个5*一个数,有的可以拆成2个5相乘*一个数.......,有的可以拆成k个5相乘*一个数,需要统计每一种拆分的个数,然后计算和。通过观察可知,