LeetCode:Factorial Trailing Zeroes

原创 2016年06月15日 12:17:17

Factorial Trailing Zeroes




Total Accepted: 61757 Total Submissions: 185808 Difficulty: Easy

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

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
 Math
Hide Similar Problems
 (H) Number of Digit One



















思路:

1.题意求n!中后缀0的个数。

2.n!=1*2*3*...*n,中的0由(2^i) * (5^j)得来。

3.即要计算min(i,j)。

4.j<=i,直观的来看:i是逢2进1,j是逢5进1。固只需计算5的个数。

例如:10!=1*2*3*4*5*6*7*8*9*10 = ..*(2^4)*...*(5^2)..

求10!中5的个数,即求 k = n/5 + n/25 + n/125 + ....+n/5^j,其中j<=n。


c++ code:

class Solution {
public:
    int trailingZeroes(int n) {
        int x = 5;
        int ret = 0;
        while(x <= n) {
            ret += n/x;
            x *= 5;
        }
	 return ret;
    }
};


或:

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


版权声明:本文为博主原创文章,转载请注明出处。

Factorial Trailing Zeroes-Leetcode

本题仍然是考察思路,属于Easy级别,有了思路后只需几行代码即可实现: class Solution { public: /* 要想若干数字之乘积末尾出现0,则这些数字的因子中必须包含...

Leetcode Problem.172—Factorial Trailing Zeroes

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

LeetCode题解——Factorial Trailing Zeroes

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

LeetCode: Factorial Trailing Zeroes

1 题目2 寻找阶乘的特点定义: 一个正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,并且有0的阶乘为1。亦即n!=1×2×3×…×n。阶乘亦可以递归方式定义:0!=1,n...

leetcode 172. Factorial Trailing Zeroes

DescriptionGiven an integer n, return the number of trailing zeroes in n!.Note: Your solution should...

LeetCode 172 Factorial Trailing Zeroes

题目描述Given an integer n, return the number of trailing zeroes in n!.Note: Your solution should be in ...

leetcode172:Factorial Trailing Zeroes

题意:求一个整数的阶乘的尾数0的个数。分析:**方法一:**对n!做质因数分解n!=2x∗3y∗5z∗...n!=2^x*3^y*5^z*... 显然0的个数等于min(x,z)min(x,z),并且...
  • hjxzb
  • hjxzb
  • 2015年04月07日 10:37
  • 461

<LeetCode OJ> 172. Factorial Trailing Zeroes

172. Factorial Trailing Zeroes My Submissions Question Total Accepted: 45801 Total Submissions: ...

【一天一道LeetCode】#172. Factorial Trailing Zeroes

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目...

[leetcode]Factorial Trailing Zeroes

博客园网址:http://www.cnblogs.com/ganganloveu/p/4193373.html Factorial Trailing Zeroes Given an int...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode:Factorial Trailing Zeroes
举报原因:
原因补充:

(最多只允许输入30个字)