題目
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
解1
public class Solution {
public int trailingZeroes(int n) {
//計算包含的2和5組成的pair的個數就可以了,一開始想錯了,還算了包含的10的個數。
//因爲5的個數比2少,所以2和5組成的pair的個數由5的個數決定。
//觀察15! = 有3個5(來自其中的5, 10, 15), 所以計算n/5就可以。
//但是25! = 有6個5(有5個5來自其中的5, 10, 15, 20, 25, 另外還有1個5來自25=(5*5)的另外一個5),
//所以除了計算n/5, 還要計算n/5/5, n/5/5/5, n/5/5/5/5, ..., n/5/5/5,,,/5直到商爲0。
int count_five = 0;
while ( n > 0) {
int k = n / 5;
count_five += k;
n = k;
}
return count_five;
}
}
解2(超時)
public class Solution {
public int trailingZeroes(int n) {
if(n<1) return 0;
int count_five=0;
for(int i=n;i>=1;i--){
if(i%5==0){
//System.out.println(i);
int N=i;
while(N%5==0){
count_five++;
N=N/5;
}
}
}
return count_five;
}
}
參考鏈接
參考鏈接:http://blog.csdn.net/feliciafay/article/details/42336835