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

    Factorial Trailing Zeroes

    问题:

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

    Note: Your solution should be in logarithmic time complexity.

    思路:

      知道思路,完全想不明白啊

    别人代码:

    public class Solution {
        public int trailingZeroes(int n) {
            if(n <= 0) return 0;
            int k = 0;
            while(n > 0)
            {
                k += n/5;
                n /= 5;
            }
            return k;
        }
    }
    View Code

    为什么??

    别人解释:看完之后才恍然大悟,大彻大悟中。。。。

     然后既然不能遍历,便只能换个思路,能够构成末尾0,其实决定因素在于1 to n  的数一共有多少个5因子。那么我们这样考虑:
    对于5 那么能够被他整除的是 5 10 15 25 30 ... 这样其实便一共有n/5,对于 25 50 这样的数包括了两个5因子,我们在后面会计算的,在考虑5的时候,结果便是 n/5。(这个时候已经考虑到25 125了 但是只考虑了一次)
    对于25 能够被整除的是 25 50 75 ...     这样,其实一共有n/25个,这时候25 中的两个5因子,变都计数了。(在上面的基础上,在考虑一次25 这样 就完成了25两次的计数 n/5/5 == n/25啊 可以统计25有多少次 )
     对于 125  同样能够被其整除的是125 625...(按照上面的方法类似的推导 即可)
    这样,是不是结果其实便是:n/5 + n/25 + n/125 ...
  • 相关阅读:
    android 颜色值参考,(有颜色图
    Virtual address cache memory, processor and multiprocessor
    VUEJS2.0源码理解--优
    qlserver、Mysql、Oracle三种数据库的优缺点总结
    三层与MVC
    数据结构 常用定义
    c语言 typedef
    C动态内存分配
    c 指针(一)
    stdlib 头文件
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4387300.html
Copyright © 2011-2022 走看看