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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© mmakun 中级黑马   /  2015-5-30 11:38  /  1080 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

看到了求1000阶乘有多少0 的问题的题,我写了个代码,感觉比较简单:
  1. public class ZeroNumber {

  2.        
  3.         public static void main(String[] args) {
  4.                 // TODO Auto-generated method stub
  5.                 int count=0;
  6.                 for(int i=1;i<=1000;i++){
  7.                         int k=i;
  8.                         while(true){
  9.                                 if((k%5==0)&&(k>=5))
  10.                                 {
  11.                                         count++;
  12.                                         k=k/5;
  13.                                        
  14.                                 }else
  15.                                 break;
  16.                         }               
  17.                 }       
  18.                 System.out.println(count+"");
  19.         }

  20. }
复制代码

5 个回复

倒序浏览
你那个读出来准确吗?给你看看这个吧,它要借助于BigInteger对象

        public static void main(String[] args) {

                //新建一个值为1的BigInteger对象 ,BigInteger 支持任意精度的整数,其数据不会丢失
                BigInteger result = new BigInteger("1");
                //声明一个变量去接收结果
                int count=0;
               
                for (int i = 2; i <= 1000; i++)

                {
                        // 调用multiply()方法 ,循环相乘,得出结果。
                        result = result.multiply(new BigInteger(i + ""));

                }
                /*System.out.println(result);*/
                // 从整数将其变为string类型
                String str = result.toString();
               
                //遍历一边str字符串
                for (int i = 0; i < str.length(); i++) {
                        //存在等于0的情况 count++得到结果
                        if (str.charAt(i)=='0') {
                                count++;
                        }
                }
                System.out.println("1000!的结果中包含0有"+count+"个");
        }

回复 使用道具 举报
Tangtang 发表于 2015-5-30 14:26
你那个读出来准确吗?给你看看这个吧,它要借助于BigInteger对象

        public static void main(String[] args ...

是准确的,你把1000换成15试试,不准确
回复 使用道具 举报
楼主的代码是阶乘后面有多少个0, 二楼的代码是最终结果共有多少个0
回复 使用道具 举报
模5是为什么啊?不懂啊
回复 使用道具 举报
有一对2与5的因子相乘就有一个0,2因子一定比5因子多(这个怎么证明的不知道,有懂得帮忙解答下),所以计算出阶乘中因子5的个数,就是后结果0的个数
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马