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].
分析:如果用arr[i] 表示f(i)有多少个0的话,那么arr[i]数组是一个递增数组,这样就可以用二分查找。首先是如下函数,计算num!有多少个0、

为防止Integer溢出,都使用 long类型。

    private long getZerosCount(long num) {
        long count = 0;
        for (long i = 5; num / i >= 1; i *= 5) {
            count += num / i;
        }
        return count;
    }

因为每出现一个5,就会多一个0,。出现一个25就会多两个0,125三个0.。。。 所以只需要计算他们出现的次数即可,因为计算5的个数的时候,25已经计算过一次,所以下次计算只需要一次即可。

通过二分法去查找符合f(x)末尾的0的个数<=k的最大x。

    private long lessThanK(int K) {
        long low = 0, high = ((long) Integer.MAX_VALUE) * 10L;
        while (low < high) {
            long mid = low + (high - low + 1) / 2;
            long count = getZerosCount(mid);
            if (count <= K) low = mid;//int自动转long去比较
            else high = mid - 1;
        }
        return low + 1;
    }
最后的代码如下:

class Solution {
    public int preimageSizeFZF(int K) {
        if (K == 0) return 5;
        else return (int) (lessThanK(K) - lessThanK(K - 1));
    }

    private long lessThanK(int K) {
        long low = 0, high = ((long) Integer.MAX_VALUE) * 10L;
        while (low < high) {
            long mid = low + (high - low + 1) / 2;
            long count = getZerosCount(mid);
            if (count <= K) low = mid;//int自动转long去比较
            else high = mid - 1;
        }
        return low + 1;
    }

    private long getZerosCount(long num) {
        long count = 0;
        for (long i = 5; num / i >= 1; i *= 5) {
            count += num / i;
        }
        return count;
    }
}




你可能感兴趣的:(java学习,java,leetcode)