经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C » 查看文章
[Algorithm] 2. Trailing Zeros
来源:cnblogs  作者:jjlovezz  时间:2018/11/6 10:17:54  对本文有异议

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

Tips

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

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

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号