c/c++语言开发共享[Algorithm] 2. Trailing Zeros

Description Description Write an algorithm which computes the number of trailing zeros in n factorial. Example 11! = 39916800, so the out should be 2 …

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     }

 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/606480.html

(0)
上一篇 2021年5月13日
下一篇 2021年5月13日

精彩推荐