172. Factorial Trailing Zeroes*

172. Factorial Trailing Zeroes*

https://leetcode.com/problems/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.

C++ 实现 1

注意 0! = 1.

思路在: 这详尽的思路令我茅塞顿开!递归非递归都有哦! 有阐述, 具体是:

仔细一想,会出现零只有一种情况嘛:2*5=10;
所以我们可以将阶乘进行因式分解,比如5=1*2*3*4*5=1*2*3*2*2*5,
共有12*5,所以结果就只有一个0嘛;有几对2*5,结果就有几个0!
所以问题就简化为找有几对2*5,能不能进一步简化捏?必须可以啊!
我们发现2的个数是远远多于5的,所以最终简化为了找出5的个数!
如果找出5的个数呢,比如20!,
从120,共有51015,20,共有45,即结尾0的个数为n/5!
这样就ok么?当然没ok,25!结果不只是25/5=5025结果有60,因为25=5*5,有两个5。所以结果f(n)=n/5+f(n/5)!

代码如下:

class Solution {
public:
    int trailingZeroes(int n) {
        return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章