LeetCode Weekly Contest 74 793. Preimage Size of Factorial Zeroes Function【二分】
2018-03-04 17:57
423 查看
793. Preimage Size of Factorial Zeroes Function
Let f(x) be the number of zeroes at the end of x!. (Recall that x! = 1 * 2 * 3 * … * x, and by convention, 0! = 1.)For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. Given K, find how many non-negative integers x have the property that f(x) = K.
Example 1:
Input: K = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.
Example 2:
Input: K = 5
Output: 0
Explanation: There is no x such that x! ends in K = 5 zeroes.
Note:
K will be an integer in the range [0, 10^9].题意: 问你有多少个数的阶乘后面有k个零
分析: 首先我们先反过来求,当知道一个数,求有多少零,我们只需不断除5即可,因为每个我们都可以分解一个2和5,从而得到一个零,然后我们二分这个答案,我们找下界,然后我们再查找k+1的下届,中间的就是答案
参考代码
class Solution { public: bool check(long long m, int K) { long long res = 0; while (m) { res += m / 5; m /= 5; } if(res >= K) { return true; } return false; } int f(int K) { long long l = 0; long long r = 1000000000000000000LL; long long res; while (l <= r) { long long mid = l + r >> 1; if(check(mid,K)) { res = mid; r = mid - 1; } else l = mid + 1; } return res; } int preimageSizeFZF(int K) { long long l = f(K); long long r = f(K + 1); return r - l; } };
相关文章推荐
- LeetCode Weekly Contest 25 之 507.Perfect Number
- LeetCode Weekly Contest 46解题思路
- leetcode Weekly Contest 67 -- 763. Partition Labels
- leetcode Weekly Contest 67 -- 765. Couples Holding Hands
- LeetCode Weekly Contest 43【总结】
- LeetCode Weekly Contest 25
- 【LeetCode】LeetCode Weekly Contest 16B
- LeetCode Weekly Contest 23 之 536.Construct Binary Tree from String
- LeetCode Weekly Contest 43解题思路
- LeetCode Weekly Contest 27
- LeetCode Weekly Contest 44解题思路
- LeetCode Weekly Contest 26解题思路
- LeetCode Weekly Contest 23
- (dp)LeetCode Weekly Contest 34 -Non-negative Integers without Consecutive Ones
- LeetCode Weekly Contest 56 Find K-th Smallest Pair Distance
- LeetCode Contest 74
- (Trie)LeetCode Weekly Contest 42 Q4 648. Replace Words
- LeetCode Weekly Contest 6
- LeetCode Weekly Contest 32 解题报告
- LeetCode Weekly Contest 39