[leetcode]172. Factorial Trailing Zeroes

题目

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

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.

解法

思路

该题就是求n的阶乘结果中末尾有几个0. 0是由2和5产生的, 所以我们只要求2或5的个数,但是2的个数远大于5,所以我们求5的个数即可。
需要注意的是5提供一个5,25提供两个5,125提供三个5,依次类推,所以这些数字我们得全部考虑进去。
最后的结果就相当于 res=n/5 + n/25 + n/125+ ....

代码(非递归)

class Solution {
    public int trailingZeroes(int n) {
        int res = 0;
        while(n > 0) {
            res += n/5;
            n /= 5;
        }
        return res;
    }
}

代码(递归)

class Solution {
    public int trailingZeroes(int n) {
       return n==0 ? 0 : n/5 + trailingZeroes(n/5);
    }
}
posted @ 2018-10-10 08:37  shinjia  阅读(140)  评论(0编辑  收藏  举报