【问题标题】:Counting numbers up and down using Recursion使用递归向上和向下计数
【发布时间】:2016-09-14 06:18:01
【问题描述】:

给定两个数字,比方说start = 1end = 4,我试图按顺序计算所有数字 up 然后 down 。不允许循环

1 2 3 4 3 2 1

我尝试编写递归函数。该函数计数正常,打印 1 2 3 4 但是当我尝试倒数时,我希望 4 3 2 1 但我进入了无限循环。原因是递归中丢失了起始值,从下向上计数时我不知道在哪里停止。

我在这上面花了 4 个小时。我们甚至可以在递归中做到这一点吗?递归是一种方式吗

public static void countUpDown(int start, int end) {
    //to pring bottom up -> 4 3 2 1
    if ( start > end  && end > 0) {
        System.out.println(end - 1);
        countUpDown(start, end - 1);    
    }

   //to print up 1 2 3 4 
    if (start <= end) {
        System.out.println("-->" + start);
        countUpDown(start + 1, end);
    }
}

【问题讨论】:

  • 任何帮助我走向正确的方向都会有所帮助

标签: java recursion


【解决方案1】:

您只需要使用递归进行计数。然后,当函数返回时,你就在下山了。这可以通过以下方式实现:

public void countUpAndDown(int start, int end) {
    System.out.println(start);
    if (end == start) return;
    countUpAndDown(start+1, end);
    System.out.println(start);
}

【讨论】:

  • 打印工作,但我认为递归上下更多是算法挑战,而不是正确打印的问题。让我们看看这对他来说是否足够。 +1
【解决方案2】:

您也许可以将其设置为从 1->3 向上计数,然后 >=4 执行 -- 向下计数到 1。

【讨论】:

  • 我已经回复你了
【解决方案3】:

试试这个

 private static int  CountUpAndDown(int end, int first, int start)
    {
        if(end==first)
        {
            return -1;
        }
        if (start > end)
        {
           System.out.println(--end);
        }
        else {
            System.out.println(start++);
        }
        return CountUpAndDown(end, first, start);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 2015-01-22
    • 1970-01-01
    • 2020-11-11
    • 2020-07-31
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    相关资源
    最近更新 更多