LeetCode *** 172. Factorial Trailing Zeroes

来源:互联网 发布:c语言pthread 编辑:程序博客网 时间:2024/05/27 12:22

题目:

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

Note: Your solution should be in logarithmic time complexity.


分析:

最终有0的话,只有可能是乘了10,或者有5存在。但是像25、125类似的,一个数有一个以上的5,那么这就是一个问题了。。。所以需要连续分析。就酱。


代码:

最初版本:

class Solution {public:    int trailingZeroes(int n) {                int total=log(n)/log(5);        int res=0;                for(int i=1;i<=total;++i){            res+=n/(pow(5,i));        }                return res;    }};

改了一下:

class Solution {public:    int trailingZeroes(int n) {                int total=log(n)/log(5);        int res=0;        int now=5;                for(int i=1;i<=total;++i){            res+=n/now;            now*=5;        }                return res;    }};

最终:

class Solution {public:    int trailingZeroes(int n) {                if(n==0)return 0;                return n/5+trailingZeroes(n/5);    }};



0 0
原创粉丝点击