Java两种方法计算出阶乘尾部连续0的个数
作者:ReganYue 时间:2021-09-03 06:04:40
第一个方法是计算出阶乘然后计算字符串的0的个数。
import java.util.Scanner;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class jc{
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
DecimalFormat a = new DecimalFormat("#");
int num;
num = reader.nextInt();
double sum=1;
for(int i=2;i<=num;i++){
sum*=i;
}
//System.out.println(sum);
//System.out.println(cal_the_number_of_zero(sum+""));
System.out.println(a.format(sum));
System.out.println(cal_the_number_of_zero(a.format(sum)));
}
public static int cal_the_number_of_zero(String str){
int num=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)=='0'){
num++;
}
else{num=0;}
}
return num;
}
}
但是当数字很大时,上面那种方法就不能计算出来了。于是我们可以利用数学方法来计算。
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int ret =0;
for(int i=n;i>=5;i--){
int tmp =i;
while(tmp%5==0){
ret++;
tmp=tmp/5;
}
}
System.out.println(ret);
}
}
https://www.nowcoder.com/questionTerminal/6ffdd7e4197c403e88c6a8aa3e7a332a
来源:https://blog.csdn.net/qq_36045898/article/details/115001582
标签:Java,阶乘,尾部0的个数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#解决文件被占用资源,无法删除或修改的方法
2023-10-25 14:39:57
Spring Boot基础学习之Mybatis操作中使用Redis做缓存详解
2023-01-19 16:35:55
![](https://img.aspxhome.com/file/2023/1/67961_0s.jpg)
Android实现悬浮对话框代码
2022-11-23 16:12:45
![](https://img.aspxhome.com/file/2023/4/88664_0s.png)
Java设计模式之命令模式详解
2023-11-15 21:18:43
elasticsearch索引index之engine读写控制结构实现
2021-12-22 00:08:07
![](https://img.aspxhome.com/file/2023/9/61299_0s.jpg)
Java string类型转换成map代码实例
2021-06-07 12:19:29
![](https://img.aspxhome.com/file/2023/3/88753_0s.png)
SpringBoot配置SSL同时支持http和https访问实现
2023-04-25 19:42:45
![](https://img.aspxhome.com/file/2023/1/70521_0s.jpg)
SpringBoot日志配置操作全面介绍
2023-03-08 14:37:54
![](https://img.aspxhome.com/file/2023/1/84331_0s.png)
Java四种常用线程池的详细介绍
2021-09-29 17:45:46
Java 实战练习之网上电商项目的实现
2021-07-17 04:23:59
![](https://img.aspxhome.com/file/2023/2/94192_0s.png)
带你走进Maven的大门-最全Maven配置及集成idea工具总结
2022-12-06 08:41:40
![](https://img.aspxhome.com/file/2023/0/60680_0s.png)
Java基础之堆内存溢出的解决
2023-11-10 20:06:30
![](https://img.aspxhome.com/file/2023/8/59338_0s.png)
shiro多验证登录代码实例及问题解决
2023-11-30 07:20:00
Java中继承thread类与实现Runnable接口的比较
2022-06-09 12:57:09
![](https://img.aspxhome.com/file/2023/8/70548_0s.jpg)
C#移除所有事件绑定的方法
2023-07-25 11:00:52
AndroidStduio3.0 使用gradle将module打包jar文件的方法
2023-07-01 06:57:20
![](https://img.aspxhome.com/file/2023/4/84224_0s.png)
Mybatis Plus select 实现只查询部分字段
2022-07-23 18:51:32
![](https://img.aspxhome.com/file/2023/9/61279_0s.jpg)
Java通过反射将 Excel 解析成对象集合实例
2023-05-22 18:49:02
![](https://img.aspxhome.com/file/2023/2/69942_0s.jpg)
利用java反射机制实现自动调用类的简单方法
2023-11-29 15:57:22
详解Java编程中线程同步以及定时启动线程的方法
2021-08-31 10:59:20