LeetCode(31)-Factorial Trailing Zeroes

题目:

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;
    }
}

你可能感兴趣的:(LeetCode,算法,factorial,zero,trailing)