[Leetcode] 172. 阶乘后的零 java

 给定一个整数 n,返回 n! 结果尾数中零的数量。

示例 1:

输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。

示例 2:

输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.

说明: 你算法的时间复杂度应为 O(log n) 

最开始我是这样写的,但是n大了的时候,会抛出StackOverFlowError(线程请求的栈深度大于虚拟机允许的深度。)

class Solution {
    public int trailingZeroes(int n) {
        int result=jiecheng(n);
        int count=0;
        while(result!=0){//求几个0
            if(result%10==0) count++;
            result/=10;
        }
        return count;
    }
    private int jiecheng(int n){//求阶乘结果
        if(n==0) return 1;
        if(n==1||n==2) return n;
        int multiply=n*jiecheng(n-1);
        return multiply;
    }
}

所以查了一下大家都是怎么实现的

1×5  → 5!  → 1个0
2×5  → 10! → 2个0
3×5  → 15! → 3个0
4×5  → 20! → 4个0
5×5  → 25! → 6个0
6×5  → 30! → 7个0
7×5  → 35! → 8个0
8×5  → 40! → 9个0
9×5  → 45! → 10个0
10×5 → 50! → 12个0
11×5 → 55! → 13个0
--------------------- 
作者:努力努力再努力Sunny 
原文:https://blog.csdn.net/z983002710/article/details/81100762 

class Solution {
    public int trailingZeroes(int n) {
        int count=0;
        while(n!=0){
            n/=5;
            count+=n;
        }
        return count;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值