Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in polynomial time complexity.

public class Solution {
    public int trailingZeroes(int n) {
        int count=0; 
        for(int i = n; i > 0 ; i--){
            if(i%5 == 0){
                count = count + fun(i);
            }
        }
        return count;
    }
    public int fun(int n){//计算n是5的几次方
        int count = 0;
        while(n % 5 == 0){
            count ++;
            n = n / 5;
        }
        return count;
    }
}

计算出5的个数也就计算出了后导零的个数

改进:只遍历5的倍数

public class Solution {
    public int trailingZeroes(int n) {
        int count=0; 
        for(int i = 5; i <= n ; i=i+5){
            count = count + fun(i);
        }
        return count;
    }
    public int fun(int n){//计算n是5的几次方
        int count = 0;
        while(n % 5 == 0){
            count ++;
            n = n / 5;
        }
        return count;
    }
}

Runtime:  420 ms

public class Solution {
    public int trailingZeroes(int n) {
        int count=0; 
        for(int i = 5; i <= n ; i=i+5){
            count++;
            if(i/5 % 5 == 0){
                int j = i / 5;
                int tmp = 0;
                while(j % 5 == 0){
                    tmp ++;
                    j = j / 5;
                }
                count = count + tmp;
            }
        }
        return count;
    }
}

Runtime:  392 ms

你可能感兴趣的:(LeetCode,factorial,z,trailing)