[Algorithm] 2. Trailing Zeros

2018-11-05 08:22:09来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Description

Write an algorithm which computes the number of trailing zeros in n factorial.

Example

11! = 39916800, so the out should be 2

Challenge

O(log N) time

Answer

 1     /*
 2      * @param n: A long integer
 3      * @return: An integer, denote the number of trailing zeros in n!
 4      */
 5     long long trailingZeros(long long n) {
 6         // write your code here, try to do it without arithmetic operators.
 7         if(n<5){
 8             return 0;
 9         }
10         else{
11             return n/5 + trailingZeros(n/5);
12         }
13     }

Tips

This solution is implemented by a recursive method, we can also use a loop method to solve this problem.

 1     /*
 2      * @param n: A long integer
 3      * @return: An integer, denote the number of trailing zeros in n!
 4      */
 5     long long trailingZeros(long long n) {
 6         // write your code here, try to do it without arithmetic operators.
 7         long long result = 0;
 8         while ( n > 0)
 9         {
10             result += n/5;
11             n /= 5;
12         }
13         
14         return result;
15     }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:GNU编译器学习 --&gt; 如何链接外部库【Linking with external

下一篇:调用当前年月日