无法使用递归打印出聚合和发散的数字序列

时间:2017-04-24 23:45:43

标签: java recursion

问题的措辞是 "编写一个方法writeSequence,它接受一个整数n作为参数并输出n个数字的对称序列,其中以1结尾的降序整数,后跟以1开头的升序整数,如下表所示:"

该表基本上是:

1 = 1
2 = 1 1
3 = 2 1 2
4 = 2 1 1 2
5 = 3 2 1 2 3
6 = 3 2 1 1 2 3

我尝试的代码是

public void writeSequence(int n){
    if (n < 1){
        throw new IllegalArgumentException();
    }
    if (n == 1){
        System.out.print(n + " ");
    }
    else if (n == 2){
        System.out.print(1 + " " + 1 + " ");
    }
    else if (n % 2 == 0){
        System.out.print(n - (n/2) + " ");
        writeSequence(n - (n/2));
        System.out.print(n - (n/2) + " ");
    }
    else{
        System.out.print(n-(n/2) + " ");
        writeSequence(n - 2 );
        System.out.print(n-(n/2)+ " ");
    }
}

对于输入1-10,我的代码没有为6,8和10生成正确的答案。非常感谢任何帮助。

编辑:

修正了标题中的拼写

编辑2:

我的结果是

1 = 1
2 = 1 1 
3 = 2 1 2
4 = 2 1 1 2
5 = 3 2 1 2 3
6 = 3 2 1 2 3 (wrong)
7 = 4 3 2 1 2 3 4
8 = 4 2 1 1 2 4 (wrong)
9 = 5 4 3 2 1 2 3 4 5
10 = 5 3 2 1 2 3 5 (wrong) 

如果有人能告诉我我在代码中出错的地方会很棒!

1 个答案:

答案 0 :(得分:2)

您的递归调用传递的值不正确。每次算法递归时,都应该将值减少2

改变这个:

writeSequence(n - (n/2));

到此:

writeSequence(n - 2);