Java练习题-求1000!的结果中包含多少个0
程序员文章站
2022-06-17 15:00:28
...
import java.math.BigDecimal;
/**
* 求1000!的结果中包含多少个0?注:1000! = 1×2×3×4×5×…×999×1000
* @author Tang
*
*/
public class Test9 {
private static final BigDecimal oneBigDecimal=new BigDecimal(1);
/**
* 计算'0'在字符串中的个数
* @param str
* @return
*/
public static int getZeroCount(String str){
int count=0;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)=='0'){
count++;
}
}
return count;
}
/**
* 计算阶乘
* @param number
* @return
*/
private static BigDecimal computeFactorial(BigDecimal number){
if (number.compareTo(oneBigDecimal)<=0) {
return oneBigDecimal;
}
return number.multiply(computeFactorial(number.subtract(oneBigDecimal)));
}
public static void main(String[] args) {
BigDecimal result = computeFactorial(new BigDecimal(1000));
System.out.println(result);
System.out.println(getZeroCount(result.toString()));
}
}
转载于:https://my.oschina.net/tangzhichao/blog/781399
上一篇: table 中th高度固定