CodeWars 给定数值的阶乘结果中包含多少0

Description:

Write a program that will calculate the number of trailing zeros in a factorial of a given number.

http://mathworld.wolfram.com/Factorial.html

N! = 1 * 2 * 3 * 4 … N

zeros(12) = 2 # 1 * 2 * 3 .. 12 = 479001600
that has 2 trailing zeros 4790016(00)
Be careful 1000! has length of 2568 digital numbers.

不需要求出阶乘结果,首先阶乘的值太大了,而我们只需要求出能够得到0的两个数的乘积就好了:

public class Solution {
  public static int zeros(int n) {
    int res = 0;
    for (int i = 5; i <= n; i *= 5) {
      res += n / i;
    }
    return res;
  }
}

My solution:

/**
 * Created by mff on 2017/4/26.
 */
public class Solution {
    public static int zeros(int n) {
//        // your beatiful code here
//    long result1 = nj(n);
//        System.out.println(result1);
//    int count =0;
//        if(result1<0){
//        return 7;
//    }
//        System.out.println(result1);
//        for(long i =result1; i>0; i=i/10){
//        if(i%10==0){
//            count++;
//        }
//        //System.out.println(i);
//    }
//        return count;
//}
//    public static long nj(int n) {
//        // your beatiful code here
//
//        if(n==0){
//            return 1l;
//        }
//        return n*nj(n-1);
        //被2整除的次数之和
        int count2 = 0;
        //被5整除的次数之和
        int count5 = 0;

        //遍历所有的数
        for (int number = 1; number <= n; number ++) {
            int dynmicNumber = number;//该数的一个复制,用于不数的整除用
            while (dynmicNumber % 2 == 0) { //统计该数能被2整除多少次,但是并不单独统计,而是统计到全局
                count2++;
                dynmicNumber /= 2;
            }
            while (dynmicNumber % 5 == 0) { //统计该数能被5整除多少次,但是并不单独统计,而是统计到全局
                count5++;
                dynmicNumber /= 5;
            }
        }

        System.out.println("结尾0的个数为:" + Math.min(count2, count5));
        return  Math.min(count2, count5);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值