zoukankan      html  css  js  c++  java
  • 【LeetCode】172

    Given an integer n, return the number of trailing zeroes in n!.

    Note: Your solution should be in logarithmic time complexity.

    Solution :计算包含的2和5组成的pair的个数,因为5的个数比2少,所以2和5组成的pair的个数由5的个数决定。 

    • 观察15! = 有3个5(来自其中的5, 10, 15), 所以计算n/5就可以。  

    • 但是25! = 有6个5(有5个5来自其中的5, 10, 15, 20, 25, 另外还有1个5来自25=(5*5)的另外一个5),
    所以除了计算n/5, 还要计算n/5/5, n/5/5/5, n/5/5/5/5, ..., n/5/5/5,,,/5直到商为0。  

     1 class Solution {
     2 public:
     3     int trailingZeroes(int n) {
     4         int ret=0;
     5         while(n){
     6             ret += n/5;
     7             n /= 5;
     8         }
     9         return ret;
    10     }
    11 };
  • 相关阅读:
    网络流 方阵移动
    NOI2019滚粗记
    PKUSC2019游记
    CQOI十二省联考游记
    数学结论题 书堆
    计算几何 大灾变
    51NOD 1773 A国的贸易
    BZOJ 3944
    51Nod 1238
    NOIP2018游记
  • 原文地址:https://www.cnblogs.com/irun/p/4705421.html
Copyright © 2011-2022 走看看