题目:求n!中含有0的个数。

分析 :这个题目很简单,关键是n的阶乘可能很大,一般的基础类型整数存不下。Java中提供了大数类,很方便,本题中就是用BigInteger类存放结果的。

 1 package huawei;
 2 
 3 import java.math.BigInteger;
 4 
 5 
 6 public final class Demo {
 7     
 8     /*
 9     功能:
10         
11     输入: 
12         
13     输出:    计算n!中有多少个0
14          
15     返回: 
16          
17     */
18     
19     public static   int getZeroCount(int n)
20     {
21         /*在这里实现功能*/
22         BigInteger N = BigInteger.valueOf(n);
23         BigInteger NFactorial = getNFactorial(N);//获取n的阶乘,保存在一个大整型里面
24         String NFactorialToString = NFactorial.toString();
25         
26         //获取结果里面0的个数
27         int total = 0;
28         
29         for(int i=0;i<NFactorialToString.length();i++) {
30             
31             if(NFactorialToString.charAt(i)=='0')
32             {
33                 total++;
34             }
35             
36         }
37         
38 
39         return total;
40     }
41     
42     //计算n的阶乘
43     public static BigInteger getNFactorial(BigInteger b) {
44         
45         if(b.equals(BigInteger.ONE)) 
46         
47         {
48             return b;
49             
50         }else {
51             
52             return b.multiply(getNFactorial(b.subtract(BigInteger.ONE)));
53             
54         }
55     }
56     
57 }

相关文章:

  • 2022-12-23
  • 2021-09-06
  • 2022-12-23
  • 2021-07-26
  • 2021-11-29
  • 2021-08-31
  • 2022-03-10
  • 2022-02-09
猜你喜欢
  • 2021-11-12
  • 2022-01-19
  • 2022-01-01
  • 2021-11-17
  • 2021-11-02
  • 2021-11-17
  • 2021-10-22
相关资源
相似解决方案