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

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

    Note: Your solution should be in logarithmic time complexity.

    Solution1:

     1 class Solution {
     2 public:
     3     int trailingZeroes(int n) {
     4         long int temp = factorial(n);
     5         int count = 0;
     6         bool finish = false;
     7         while(!finish){
     8             if(temp % 10 == 0){
     9                 count++;
    10                 temp /= 10;
    11             }
    12             else finish = true;
    13         }
    14         return count;
    15     }
    16     long int factorial(int n){
    17         if(n == 0) return 1;
    18         else return n*factorial(n-1);
    19     }
    20 };

    结果显示超时,所以只能换个思维。每当出现5的时候,由于在这之前已经出现了偶数,所以可以产生1个0。遇到25、50、75、100、125等25的倍数时,0的个数相应增加。当在草稿纸上每5个数写出5~125的output时,可以发现很明显的规律,如以下代码:

    Solution2:

     1 class Solution {
     2 public:
     3     int trailingZeroes(int n) {
     4         if(n == 0) return 0;
     5         
     6         int count = 0;
     7         while(n >= 5){
     8             count += n / 5;
     9             n /= 5;
    10         }
    11         return count;
    12     }
    13 };
  • 相关阅读:
    HTML初步学习7
    HTML初步学习6
    HTML初步学习5
    HTML初步学习4
    poj3449Geometric Shapes
    poj2074Line of Sight(直线相交)
    2014 Multi-University Training Contest 4
    poj3347Kadj Squares
    poj1556The Doors
    poj3608Bridge Across Islands(凸包间最小距离)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4415451.html
Copyright © 2011-2022 走看看