Leetcode_09 Preimage Size of Factorial Zeroes Function

题目: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].

原理:求末尾零的个数,如函数numOfTraillingZeros,

   1.   首先,2*5 = 10,产生0,那么0的个数,就是求2,5的个数,由于2的个数远多于5,因此问题转换为求5的个数

   2.   1~24之间5的个数为 x/5, 24/5 = 4,因此24!有4个0;   而25自身包含两个5,因此25!有6个0,末尾有5个0的数字是不存在的,同样125包含3个5... ...

   3.    对于末尾有k个0的数,假设k存在,则 x 的范围为 0 ~ 5*(k+1) ,而具体k是否存在,可以通过二分搜索法查找,通过函数

          numOfTraillingZeros(x) == k ? 来验证

class Solution {
public:
    long numsOfZero(long x)
    {
        long res = 0;
        while(x > 0)
        {
            res += x/5;
            x = x/5;
        }
        return res;
    }
    int preimageSizeFZF(int K) {
     
        long l = 0 , r = 5L*(K+1);
        while(l<=r)
        {
            long mid = l + (r - l) / 2 ;
            long bk = numsOfZero(mid);
            if(bk == K)    return 5;
            else if( bk < K)
                l = mid + 1;
            else if(bk > K)
                r = mid - 1;
        }
        return 0;
    }
};

 

 

 

 

 

你可能感兴趣的:(刷题,C/C++)