黑马程序员技术交流社区
标题:
【编程挑战(新人)】
[打印本页]
作者:
返璞归真
时间:
2014-11-15 13:46
标题:
【编程挑战(新人)】
求1000的阶乘结果中所有零的个数。{:2_41:}
作者:
返璞归真
时间:
2014-11-15 13:48
欢迎大家来讨论哈,说说自己的想法也好
作者:
kang3214
时间:
2014-11-15 14:02
用递归决解
作者:
返璞归真
时间:
2014-11-15 14:05
kang3214 发表于 2014-11-15 14:02
用递归决解
兄弟啊,递归不行的,结果的位数2000多位。。。
作者:
福禄娃
时间:
2014-11-15 20:54
import java.math.*;
/**
* 第9题 求1000!的结果中包含多少个0?注:1000! = 1×2×3×4×5×...×999×1000
*/
public class Test9 {
/*
* 思路:
* 1000!这种大数乘法,需要使用BigInteger
* 先计算出1000!的结果,然后循环取出字符串中的字符,
* 判断一共有多少个0.
*/
public static void main(String[] args)
{
String jieChengRes = jieCheng().toString();
prin("1000!的运算结果为:"+jieChengRes);
int zeroCount = returnZeroCount(jieChengRes);
prin("结果中一共包含: "+zeroCount+" 个零。");
}
//1.计算出1000!的结果。
public static BigInteger jieCheng()
{
BigInteger result = new BigInteger("1");
for (int i = 1; i <= 1000; i++)
{
BigInteger num = new BigInteger(String.valueOf(i));
// 大数运算与基本数据类型不同,不能使用*运算符,用独有的multiply()方法
result = result.multiply(num);
}
return result;
}
//循环取出字符串中的字符,并记录一共有多少个0.
public static int returnZeroCount(String res)
{
int count = 0;
for (int i = 0; i < res.length(); i++)
{
String str = String.valueOf(res.charAt(i));
if(str.equals("0"))
{
count++;
}
}
return count;
}
//换行打印通用方法
public static void prin(Object obj)
{
System.out.println(obj);
}
}
复制代码
一切尽在代码之中~。
作者:
田峻菘
时间:
2014-11-15 22:37
我的测试题答案:
package com.itheima;
import java.math.BigInteger;
/**
* 第9题:求1000!的结果中包含多少个0?注:1000! = 1×2×3×4×5×...×999×1000
* 思路:
* 1,创建BigInteger对象
* 2,定义一个变量计数
* 3,for循环计算1000!结果装入BigInteger对象中
* 4,把BigInteger对象转为String类型
* 5,for循环遍历String,若遇'0',则计数变量加1
* 6,打印计数结果
* @author
*/
public class Test9 {
public static void main(String[] args) {
// 创建值为1的BigInteger对象factorial
BigInteger factorial = new BigInteger("1");
// 定义一个变量count计数
int count = 0;
// for循环计算1000!结果装入factorial中
for (int i = 2; i <= 1000; i++) {
factorial = factorial.multiply(new BigInteger(i + ""));
}
// 把factorial转为String类型
String s = factorial.toString();
// 遍历s,若遇'0',则count++计数
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '0')
count++;
}
// 输出计数结果
System.out.println("1000!的结果包含0的个数为:" + count);
}
}
复制代码
作者:
返璞归真
时间:
2014-11-16 06:54
使用数组也可以解决(不用BigInteger类),大家可以尝试下哈
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2