首页 > 解决方案 > 更改序列的顺序

问题描述

我正在尝试使用没有循环的递归打印序列。使用下面的代码,我得到了正确的输出;但是,它是从大到小,我希望它从小到大。最好的方法是什么?目前我得到输出:

22 19 16 13 10

但我希望它被扭转。

public class Recursion
{
    public static void main(String[] args)
    {
        sequence(5);
    }

    public static void sequence(int n)
    {
        if (n >= 1)
        {
            int x = ((3*n) + 7);
            System.out.print(x + " ");
            sequence(n-1);
        }
    }
}

标签: java

解决方案


Right now you print the computed value, and then you recurse with the next (decremented) n-value, which prints the next value in the sequence.

All you need to do is recurse first, and then print the current computed value after. This will print the "next" value of the sequence and then finish printing the just-computed "current" value.

public class Recursion
{
    public static void main(String[] args)
    {
        sequence(5);
        System.out.println();
    }

    public static void sequence(int n)
    {
        if (n >= 1)
        {
            int x = ((3*n) + 7);
            sequence(n-1);
            System.out.print(x + " ");  // changed order of recursive call and print
        }
    }
}

推荐阅读