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);

 

转载于:https://www.cnblogs.com/gogolee/p/6642993.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值