码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Factorial Trailing Zeroe

时间:2015-04-11 16:21:43      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

Factorial Trailing Zeroes

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

Note: Your solution should be in logarithmic time complexity.

解题思路:

n!=2^x*3^y*5^z...,注意到一个2和一个5贡献一个末尾的0,因此只需计算min(x,z)即可。又因为n/2和n/5分别表示n!中的因子能被2和5整除的个数,n/2>=n/5,因此min(x, z)=z。我们只需要计算z即可。

如何计算z呢?n/5表示n!中被5整数的个数(贡献至少一个0), n/(5^2)表示被25整除的个数(贡献至少2个0)...,因此z的计算代码如下:
class Solution {
public:
    int trailingZeroes(int n) {
        int ret = 0;
        while(n)
        {
            ret += n /= 5;
        }
        return ret;
    }
};
扩展思维:
曾经做过,30!的三进制表示中,末尾0的个数有多少个?注意到在三进制中,每逢三便给结果贡献一个0,因此0的个数为30/3+30/9+30/27=14。注意这里的除法是整数除法。

[LeetCode] Factorial Trailing Zeroe

标签:

原文地址:http://blog.csdn.net/kangrydotnet/article/details/44995811

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!