- import java.math.BigInteger;
- import java.util.regex.*;
- import java.util.*;
- class Test2{
-
- public static void main(String ars[]){
- Test2 test2 = new Test2();
- test2.jieCheng(1000);
- }
-
- public void jieCheng(int number){
- BigInteger res = new BigInteger("1");
-
- for (int i = 1; i <= number; i++) {
- BigInteger num = new BigInteger(String.valueOf(i));
- res = res.multiply(num); //相当于res * = num;,但是不是基本数据类型,不能使用*运算符
- }
- String str = res.toString();
- int allZero = allZeroCount(str);
- int lastZro =lastZeroCount(str);
- System.out.println(number+"的阶乘为:"+"\n"+str);
- System.out.println(number+"的阶乘中所有的0的个数:"+allZero);
- System.out.println(number+"的阶乘中末尾的0的个数:"+lastZro);
- }
-
- //求阶乘结果末尾的0的个数
- public int lastZeroCount(String str){
- int count = 0;
- char regex = '0';
- int length = str.length();
- int index = length-1;
- while(str.charAt(index)==regex){
- count++;
- index--;
- }
- return count;
- }
-
- //求阶乘结果所有的0的个数
- public int allZeroCount(String str){
- int count = 0;
- String regex = "0";
- Pattern p = Pattern.compile(regex);
- Matcher m = p.matcher(str);
- while (m.find())
- {
- count++;
- }
- return count;
- }
- }
复制代码 |