A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 习惯就好 中级黑马   /  2015-3-9 20:39  /  1131 人查看  /  10 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. package com.heima;

  2. import java.math.BigInteger;

  3. /*
  4. * 问题:求1000!的结果中包含多少个0
  5. 1000! = 1×2×3×4×5×...×999×1000
  6. 遇10为零*/

  7. public class Test2 {
  8.         public static void main(String [] asd)
  9.         {
  10.             BigInteger bt=new BigInteger("1000");
  11.           
  12.             for(int x=1;x<1000;x++)
  13.             {
  14.                    
  15.                     BigInteger aa=new BigInteger(String.valueOf(x));
  16.                     bt=bt.multiply(aa);
  17.             }
  18.             //BigInteger aa=bt.multiply(bt);
  19.             String str=bt.toString();
  20.             System.out.println(str);
  21.             int count=0;
  22.             int dex=0;
  23.             String strr="0";
  24.                     while((dex=str.indexOf(strr,dex))!=-1)
  25.                     {
  26.                             dex++;
  27.                             count++;
  28.                     }               
  29.             System.out.println("零的个数有:"+count);
  30.         }
  31. }
复制代码


10 个回复

倒序浏览
面试会考这个类?这个类老师讲过吗
回复 使用道具 举报
public class Test {
        public static void main(String[] args)
        {
                int count = 0;
                long mul = 1;
                for(int i = 1;i<=100;i++)
                {
                        mul=mul*i;
                }
                System.out.println("值为"+mul);
                for(int j=10;mul%j==0;mul=mul/j)
                        count++;
                System.out.println("零的个数为:"+count);
        }

}
这样做电脑会不会死
回复 使用道具 举报
public class Test {
        public static void main(String[] args)
        {
                int count = 0;
                int mul = 1;
                for(int i = 1,j=10;i<=1000;i++)
                {
                        mul=mul*i;
                        while(mul%j==0)
                        {
                                mul=mul/10;
                                count++;
                        }
                       
                }
                System.out.println("零的个数为:"+count);
        }
}
改一下,数字一直在蹦,一直不停
回复 使用道具 举报
你这种算法不行,首先mul的值会溢出,所以运行时光标总是闪,第二你每运行到10的倍数时mul就会变回这样你只能算出末尾带零的个数,并不能算出阶乘结果中的所有零的个数。你自己可以将1000改成20,然后将mul的类型改成long类型   先将while语句注释掉,看看阶乘的结果是多少个零,然后加上while语句看看是结尾零的个数不
回复 使用道具 举报
佟金 发表于 2015-3-9 22:39
public class Test {
        public static void main(String[] args)
        {

内存溢出啊
回复 使用道具 举报
佟金 发表于 2015-3-9 22:57
public class Test {
        public static void main(String[] args)
        {

i=100时count++显然是错误的
回复 使用道具 举报
这个思路就是,因为只有2*5 才有零的出现,所以可以统计一下 1。。。1000有多少个2,和5,最后取个数少的那个就是0的个数
回复 使用道具 举报
看来考试的内容还是有点难的哇。。。
回复 使用道具 举报
我去,这个是面试题?不明觉厉啊!
回复 使用道具 举报
这内容有点难呀。。。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马