【leetcode】Factorial Trailing Zeroes

来源:互联网 发布:java里字段 编辑:程序博客网 时间:2024/04/28 09:11

Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.

思路:
阿里算法工程师笔试的一个选择题。其实就是计算其中5的个数就行。算算从1到n有几个5的倍数。但是这个方法会超时(方法二),方法一思路是一样的,不会超时,因为n一直减少。
方法1:

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

方法2:

class Solution {public:    int trailingZeroes(int n) {        if(n==0) return 0;        int res=0;        for(int i=1;i<=n;i++)        {            int temp=i;            while(temp%5==0)            {                res++;                temp=temp/5;            }        }        return res;    }};
0 0
原创粉丝点击