黑马程序员技术交流社区

标题: 求1000阶乘,结果统计零出现的次数。 [打印本页]

作者: 黑马生涯    时间: 2015-5-29 23:40
标题: 求1000阶乘,结果统计零出现的次数。
有大神能说下思路吗?
用递归,完全没法。找不到出口和规律了。、。。。
作者: Amu    时间: 2015-5-29 23:47
引用BigInteger这个类 有意外惊喜
作者: 人在旅途~东营    时间: 2015-5-29 23:57
你坑不坑啊,1000的阶乘多大你算过么,都超出范围了
作者: JavaStudy770    时间: 2015-5-30 00:49
都超范围了,递归搞不了
  1. package it.heima.exercise;

  2. public class Test {

  3.         public static void main(String[] args) {
  4.                 //times(2);
  5.                 System.out.println(times(23));
  6.         }
  7.        
  8.         public static long times(long n) {
  9.                
  10.                 if(n == 1) {
  11.                         return 1;
  12.                 } else {
  13.                         return n*times(n-1);
  14.                 }
  15.                
  16.         }
  17.        
  18. }
复制代码

作者: forTomorrow    时间: 2015-5-30 08:33
额,会内存溢出吧
作者: Always,    时间: 2015-5-30 08:47
               、、、、、这个有点闹偶
作者: mmakun    时间: 2015-5-30 11:20
判断1到1000的每个数各能被5整除几次,能整除几次加几
作者: Tangtang    时间: 2015-5-30 14:17
注释很详细了,思路我就不多说了吧


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+"个");
        }




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