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

© LShu 中级黑马   /  2016-9-6 16:55  /  443 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

大神们能解答一下吗?
*有一组数的规律如下:
* 1   1    2    4    7     13      24
*需求:获取第八个数的值
package com.heima.practise;

public class Test05_01 {
        public static void main(String[] args) {
                System.out.println(fun(8));
        }
public static int fun(int num) {
                if (num == 1 || num == 2) {
                        return 1;
                }else if (num == 2) {
                        return 2;
                }else {
                        return fun(num - 3) + fun(num - 2) + fun(num - 1);
                }
        }
}

2 个回复

倒序浏览
else if (num == 2) {
                        return 2;
这个应该是numm==3 呀
回复 使用道具 举报
/*
* *有一组数的规律如下:
* 1   1    2    4    7     13      24
*需求:获取第八个数的值
*/
        public static void main(String[] args) {
                System.out.println(fun(7));
        }
        public static int fun(int num) {
        if (num == 1 || num == 2) {
                return 1;
        }else if (num == 3) {//你输的是2
                return 2;
        }else {
                return fun(num - 3) + fun(num - 2) + fun(num - 1);
        }
}
用你的程序跑,居然内存溢出了,因为你低个判断条件输错了,程序不停地循环调用,分分钟就溢出了。递归就是这个毛病,动不动就内存溢出
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马