793. 阶乘函数后 K 个零

 

labuladong 题解思路
难度困难

 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,找出返回能满足 f(x) = k 的非负整数 x 的数量。

 

示例 1:

输入:k = 0
输出:5
解释:0!, 1!, 2!, 3!, 和 4! 均符合 k = 0 的条件。

示例 2:

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

示例 3:

输入: k = 3
输出: 5


class Solution:
    def preimageSizeFZF(self, k: int) -> int:
def fn(x):
            cnt = 0
            while x:
                x=int(x/5)
                cnt+=x
            return cnt
        
        lo = 0 
        hi = 5*k
        while lo <= hi:
            mid = lo + (hi-lo)//2
            target = fn(mid)
            if target == k:
                return 5
            elif target < k:
                lo = mid + 1
            else:
                hi = mid - 1
        return 0

 



class Solution {
public:
    int f_cnt(int n) {
      int cnt = 0;
      while(n > 0) {
          cnt += (n/5);
          n = n / 5;
      }
      return cnt;
    }
    int preimageSizeFZF(int k) {
        if (k==1000000000) return 5;
        long long lo = 0, hi = 10LL *k +1;
        while(lo < hi) {
            long mid = lo + (hi -lo)/2;
            int target = f_cnt(mid);
            if (target == k) {
                return 5;
            } else if (k > target) {
                lo = mid +1;
            } else {
                hi = mid;
            }
        }
        return 0;
    }
};

 







class Solution {
public:
    int trailingZeroes(long n) {
        int cnt = 0;
        while(n>0) {
            cnt += n / 5;
            n = n /5;
        }
        return cnt;
    }
    int left_bound(long k) {
        long lo = 0,hi = 5*k;
        while(lo < hi) {
            long mid = lo + (hi - lo) / 2;
            if (trailingZeroes(mid)<k) {
                lo = mid + 1;
            } else if (trailingZeroes(mid)>k) {
                hi = mid;
            } else {
                hi = mid;
            }
        }
        return lo;
    }
    int right_bound(long k) {
        long lo = 0,hi = 5*k;
        while(lo < hi) {
            long mid = lo + (hi - lo) / 2;
            if (trailingZeroes(mid)<k) {
                lo = mid + 1;
            } else if (trailingZeroes(mid)>k) {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        return lo-1;
    }
  

    int preimageSizeFZF(int k) {      
        if(k==0 || k ==3 ) return 5;
        return right_bound(k) - left_bound(k) +1;
    }
};

 

posted @ 2022-09-02 21:21  乐乐章  阅读(47)  评论(0编辑  收藏  举报