[leetcode] 172.Factorial Trailing Zeroes

来源:互联网 发布:lvs 算法 编辑:程序博客网 时间:2024/05/19 12:15

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

Note: Your solution should be in logarithmic time complexity.
题意:
给定一个整数n,返回n!的末尾的0的个数。
思路:
首先能够出现0是末尾是5的数乘上2的倍数或者末尾是0的数。而且是2的倍数的数肯定比末尾是5的数多,所以我们只要统计是5的倍数的这些数字。比如当n=100的时候,有100/5=20个数字是5的倍数,但是再细想一下,有的数字比如25或者75或者100各供应了两个5,也就是我们需要统计25的倍数有哪几个,100/25=4,再统计供应了三个5的数字有哪几个100/125=0,所以停止寻找,最多的就是供应两个5的数字。把5的倍数的数的个数加上25倍数的数的个数等等全部加起来,把所有贡献的5都加起来,就是最终供应的0的数量。
以上。
代码如下:

class Solution {public:    int trailingZeroes(int n) {        if(n == 0)return 0;        int count = 0;        while(n /= 5) count += n;        return count;    }};
0 0
原创粉丝点击