zoukankan      html  css  js  c++  java
  • Leetcode 172 Factorial Trailing Zeroes

    1、题目要求

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

    Note: Your solution should be in logarithmic time complexity.

    题目意思是求n的阶乘后面末尾0的个数,并且时间复杂度是对数级别。

    2、分析

         一个数 n 的阶乘末尾有多少个 0 取决于从 1 到 n 的个数的因子中 2 和 5 的个数, 而 2 的个数是远远多余 5 的个数的, 因此求出 5 的个数即可. 题解中给出的求解因子 5 的个数的方法是用 n 不断除以 5, 直到结果为 0, 然后把中间得到的结果累加. 例如, 100/5 = 20, 20/5 = 4, 4/5 = 0, 则 1 到 100 中因子 5 的个数为 (20 + 4 + 0) = 24 个, 即 100 的阶乘末尾有 24 个 0. 其实不断除以 5, 是因为每间隔 5 个数有一个数可以被 5 整除, 然后在这些可被 5 整除的数中, 每间隔 5 个数又有一个可以被 25 整除, 故要再除一次, ... 直到结果为 0, 表示没有能继续被 5 整除的数了. 

    代码如下:

     1 class Solution {
     2 public:
     3     int trailingZeroes(int n) 
     4     {
     5         int counter=0;  //the counter!
     6         int k=n;
     7      
     8          while(k>=5)
     9          {
    10             k=k/5;
    11             counter+=k;
    12          }
    13      
    14         return counter;
    15     }
    16 };
  • 相关阅读:
    Delimiter must not be alphanumeric or backslash php
    mysql replace用法
    MySQL transaction
    最大子数组问题
    LUP分解法求解线性方程组
    PHP和MySQL Web开发从新手到高手,第9天-总结
    DRBD+Heartbeat+mysql 高可用性负载均衡
    优秀博客网址
    rsync+inotify 实时同步数据
    Bugfree 搭建
  • 原文地址:https://www.cnblogs.com/LCCRNblog/p/4392402.html
Copyright © 2011-2022 走看看