LeetCode 172.Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Credits:Special thanks to @ts for adding this problem and creating all test cases.

 

也就是求阶乘结果,尾数有几个0,比如,

5!= 120 , 末尾有一个0.

10! =3628800, 末尾有两个0.

 

这道题能想到的第一个思路是,先求出给定number的阶乘,然后一直/10算出尾数有几个0. 

function factorial(n) {
 let result = 1;  
 while( n > 1) {
   result = result * n;
   n--;
 }
 return result;
}

function getResult() {
    var index = 0;
   if(result % 10 == 0) {
    while(result % 10 == 0) {
          result = result / 10;
        index++;
    }
  } 
return result;
    
}

这个有一个问题就是,当n特别大的时候,阶乘结果会超出Number能表示的整数最大值(Number类型统一按浮点数处理,64位存储,整数是按最大54位来算最大最小数的,否则会丧失精度;某些操作(如数组索引还有位操作)是按32位处理的)。所以如果执行%运算的话会出现错误。

去搜了下网上其他人的解答,思路还是挺好的,判断5出现的次数,毕竟2*5 = 10~ 

然后就有floor(n/5) + floor(n/5/5) + ....floor(n/5/5/5...) 直到n/5取零为止。注意js中不像java,可以设定int值取整,js中我们需要

通过Math.floor向下取整才可以。

代码如下:

function caculate(num) {
    let result = 0;
    while ( num > 0) {
        result += Math.floor( num / 5 );
        num = Math.floor(num / 5 );
    }
    return result;
}
caculate(104);

 

posted @ 2017-03-30 01:19  一片叶子啊  阅读(145)  评论(0编辑  收藏  举报