您的位置:首页 > 编程语言

leetcode:172 Factorial Trailing Zeroes-每日编程第二十四题

2015-12-15 20:32 489 查看
Factorial Trailing Zeroes

Total
Accepted: 44351 Total
Submissions: 144160 Difficulty: Easy

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

Note: Your solution should be in logarithmic time complexity.
思路:
1).n!=n*(n-1)*(n-2)*...*2*1,只有当因子有2,5的时候,在n!的末尾才会产生10.

2).因为5>2,无论n为多大,在n!当中,5的数量肯定比2少。所以,我们只需要计算n!有多少个因子5就行了。

3).循环体可以这么理解,第一次循环,有几个5的倍数,第二次循环,有几个25的倍数..第m次循环,有几个5^m的倍数。直到n<5^m。

class Solution {
public:
    int trailingZeroes(int n) {
        int sum = 0;
        while(n>0){
            sum+=n/5;
            n/=5;
        }
        return sum;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: