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

leetcode[172]Factorial Trailing Zeroes

时间:2015-02-09 00:37:06      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:

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

Note: Your solution should be in logarithmic time complexity.

给定一个整数n,返回n!(n的阶乘)数字中的后缀0的个数。

n!的后缀0总是由质因子2和质因子5相乘得来的。2的个数大于等于5的个数,计算出5的个数问题就解决了。

n!后缀0的个数 = n!质因子中5的个数 = floor(n/5) + floor(n/25) + floor(n/125) + ....

class Solution {
public:
/**
n!后缀0的个数 = n!质因子中5的个数
              = floor(n/5) + floor(n/25) + floor(n/125) + ....
*/
    int trailingZeroes(int n) {
       int res=0;
       while(n/5)
       {
           n/=5;
           res+=n;
       }
       return res;
    }
};

 

leetcode[172]Factorial Trailing Zeroes

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4280664.html

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