设为首页 加入收藏

TOP

[Algorithm] 2. Trailing Zeros
2018-11-05 14:08:44 】 浏览:39
Tags:Algorithm Trailing Zeros

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     }

 


编程开发网
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇珂朵莉树(Chtholly Tree)学习笔记 下一篇GNU编译器学习 --> 如何链接外..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

array(4) { ["type"]=> int(8) ["message"]=> string(24) "Undefined variable: jobs" ["file"]=> string(32) "/mnt/wp/cppentry/do/bencandy.php" ["line"]=> int(214) }