黑马程序员技术交流社区

标题: 求1000!的结果中包含多少个0? [打印本页]

作者: 李志鹏    时间: 2015-6-2 11:33
标题: 求1000!的结果中包含多少个0?
  1. import java.math.BigInteger;

  2. public class Test9 {

  3.         /**
  4.          * 求1000!的结果中包含多少个0?注:1000! = 1×2×3×4×5×...×999×1000
  5.          *
  6.          * @param args
  7.          */
  8.         public static void main(String[] args) {

  9.                 // 新建一个值为1的BigInteger对象
  10.                 BigInteger result = new BigInteger("1");

  11.                 // 计数值为0
  12.                 int count = 0;
  13.                
  14.                 // 循环相乘,得出结果。
  15.                 for (int i = 2; i <= 1000; i++) {
  16.                         result = result.multiply(new BigInteger(i + ""));
  17.                 }
  18.                
  19.                 // 将其变为string类型
  20.                 String str = result.toString();

  21.                 // 将结果(字符串)遍历一遍。
  22.                 for (int i = 0; i < str.length(); i++) {

  23.                         // 当有"0"时候,count++作为计数。
  24.                         if (str.charAt(i) == '0') {
  25.                                 // 计数,每有一个0就增加1
  26.                                 count++;
  27.                         }
  28.                 }

  29.                 // 输出结果。
  30.                 System.out.println(count);
  31.         }

  32. }
复制代码

作者: qq853636281    时间: 2015-6-2 18:49
本帖最后由 qq853636281 于 2015-6-2 18:58 编辑

BigInteger   这个类 真是好东西,好像就是为了求1000!  而存在一样!

但是这行代码是什么意思呢   result = result.multiply(new BigInteger(i + ""));   

这个 (i+"") 表示什么呢?,查了API对不上构造方法啊    

是字符串吗?

作者: 中平    时间: 2015-6-2 19:10
这个方法感觉不好,求1000!中的0的个数一个是有技巧的
作者: tougboy    时间: 2015-6-2 21:18
好像是传字符串进入比较简单  他就都转成字符串穿进去了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2