首页 > 代码库 > 【LeetCode】Factorial Trailing Zeroes (2 solutions)
【LeetCode】Factorial Trailing Zeroes (2 solutions)
Factorial Trailing Zeroes
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.
对n!做质因数分解n!=2x*3y*5z*...
显然0的个数等于min(x,z),并且min(x,z)==z
解法一:
从1到n中提取所有的5
class Solution {public: int trailingZeroes(int n) { int ret = 0; for(int i = 1; i <= n; i ++) { int tmp = i; while(tmp%5 == 0) { ret ++; tmp /= 5; } } return ret; }};
解法二:
由上述分析可以看出,起作用的只有被5整除的那些数。能不能只对这些数进行计数呢?
存在这样的规律:[n/k]代表1~n中能被k整除的个数。
因此解法一可以转化为解法二
class Solution {public: int trailingZeroes(int n) { int ret = 0; while(n) { ret += n/5; n /= 5; } return ret; }};
【LeetCode】Factorial Trailing Zeroes (2 solutions)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。