793. 阶乘函数后K个零

f(x) 是 x! 末尾是0的数量。(回想一下 x! = 1 * 2 * 3 * … * x,且0! = 1)

例如, f(3) = 0 ,因为3! = 6的末尾没有0;而 f(11) = 2 ,因为11!= 39916800末端有2个0。给定 K,找出多少个非负整数x ,有 f(x) = K 的性质。

示例 1:
输入:K = 0
输出:5
解释: 0!, 1!, 2!, 3!, and 4! 均符合 K = 0 的条件。

示例 2:
输入:K = 5
输出:0
解释:没有匹配到这样的 x!,符合K = 5 的条件。

二分法 4ms

class Solution {
public:
    int64_t trailingZeroes(int64_t n) {
        int64_t count_five = 0;  
        while(n > 0){  
            int64_t k = n/5;  
            count_five += k;  
            n = k;  
        }  
        return count_five;    
    }
    int64_t getMinimal(int64_t K){
        int64_t start = 0;
        int64_t end = (int64_t)2*INT_MAX;
        while(start <end){
            int64_t pivot = (end+start)/2;
            if(trailingZeroes(pivot) < K)
                start = pivot+1;
            else
                end = pivot;
        }
        return start;
    }
    int64_t preimageSizeFZF(int64_t K) {    return getMinimal(K+1)-getMinimal(K);
    }
};

要求我们找出所有数字n的个数,使得n!结尾有K个0。使用非常规二分搜索方法,在结果可能的范围内查找满足条件的最小值,这里使用了Leetcode 172 Factorial Trailing Zeroes中的函数,然后在getMinimal函数中找到结尾有K个0的最小值,然后getMinimal(K+1)-getMinimal(K)即可。

找规律 0ms

int preimageSizeFZF(int K) {
    int last=1;
    while(last<K)
        last=5*last+1;
    while(last>1){
        if(last-1==K)
            return 0;
        last=(last-1)/5;
        K%=last;
    }
    return 5;
}

猜你喜欢

转载自blog.csdn.net/weixin_42054167/article/details/92799150