zoukankan      html  css  js  c++  java
  • [LeetCode]172. Factorial Trailing Zeroes

    题目描述:

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

    Note: Your solution should be in logarithmic time complexity.

    思路:

     求n的阶乘最后面连续的0的个数,且时间复杂度在log(n)
     直接思路:
     求n的阶乘,记为sum,然后对10取余,若为0则计数+1,否则退出
     计数即为末位0的个数
     但是只能计算到12的阶乘,13及以后的阶乘就会int溢出,出现错误,而且时间复杂度巨高

     修改思路:
     只有2和5相乘的时候,末位才会出现0.所以只要统计阶乘中出现2和5的个数即可。
     n = 5: 5!的质因子中 (2 * 2 * 2 * 3 * 5)包含一个5和三个2。因而后缀0的个数是1。
     n = 11: 11!的质因子中(2^8 * 3^4 * 5^2 * 7)包含两个5和三个2。于是后缀0的个数就是2。
     由实际情况很容易发现,阶乘中2出现的次数远远大于5出现的次数。所以只要统计5出现的次数即可
     递归求n/5的个数即可
     n/5可知n里面包含几个5,而5的幂次里包含多个5 如25有2个5,125有3个5
     计算5的个数时, 最简单的方法是 SUM(N/5^1, N/5^2, N/5^3...)

     1 public class Solution172 {
     2     public int trailingZeroes(int n) {
     3         //直接思路
     4     /*    int count=0;
     5         int sum = 1;
     6         for(int i = n; i>0;i--){
     7             sum = sum * i;
     8         }
     9         while(sum%10 == 0){
    10             sum = sum/10;
    11             count++;
    12         }
    13         return count;
    14         */
    15         int count = 0;
    16         while(n>0){
    17             count += n/5;
    18             n = n/5;
    19         }
    20         return count;
    21     }
    22 
    23     public static void main(String[] args) {
    24         // TODO Auto-generated method stub
    25         Solution172 solution172 = new Solution172();
    26         int n = 13;
    27         System.out.println(solution172.trailingZeroes(n));
    28     }
    29 
    30 }
  • 相关阅读:
    《javascript高级程序设计》第六章总结
    电子邮件写信页面开发代码
    JSON和XML的比较
    2014前端工程师基础课程作业
    cookie 和session 的区别详解
    substring()、slice()和substr()方法辨析
    Number()、parseInt()和parseFloat()辨析
    《javascript高级程序设计》第十三章知识点
    angular debounce 搜索去抖动/防抖
    js四舍五入保留两位小数的方法
  • 原文地址:https://www.cnblogs.com/zlz099/p/8194642.html
Copyright © 2011-2022 走看看