題目:
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
思路:
題意是要求一個數字的階乘,末尾有多少個0 要求是對數級別的時間,所以考慮用遞歸 分析一下,產生一個10,後面加0,找到所有的2*5,或者2的次方×5的次方,任何情況下因子2的個數永遠大於5 所以只需要計算因子5的個數,(25*4 = 100),算2個5 -
代碼:
class Solution {
/*
* param n: As desciption
* return: An integer, denote the number of trailing zeros in n!
*/
public long trailingZeros(long n) {
// write your code here
return n / 5 == 0 ? 0 : n /5 + trailingZeros(n / 5);
}
};
暴力方法:(不推薦)
public class Solution {
public int trailingZeroes(int n) {
int count = 0;
if(get(n) == 0){
return 1;
}
int sum = get(n);
while(sum > 0){
if(sum % 10 == 0){
count++;
}
sum = sum /10;
}
return sum;
}
public int get(int n){
int all = 0;
if(n == 0){
return 0;
}
for(int i = 1;i <= n;i++){
all = all*i;
}
return all;
}
}