如何在 java 中用递归反转数字序列

How to reverse a sequence of numbers with recursion in java

我完全被这段代码困住了,任务很简单:“给定一个数字 n 或值,在控制台上打印从 n 到 1 和从 1 到 n 的序列(重复数字 1 所以它应该是这样的 '5432112345').

递归本身不是问题,真正的问题是第二部分,因为我不能仅使用任何其他变量 n。我无法在任何地方存储起始值,因为每次我调用该方法时它都会被实现。

目前的代码如下:

public int mirrorRecursive(Integer value){
       if (value < 1){        //in case the given value is less than 1 it won't print anything
            return value;
        }
        if(value == 1){        //in case the value is 1, it will be printed and stop the calling
            System.out.print(value);
        }else{                 //in case the value is not 1 or less, it will print and call again the method
            System.out.print(value);
            mirrorRecursive(--value);
        }

        return value;
}

我不确定该方法返回的值有什么用,但为了打印所需的输出,您只需要:

public static int mirrorRecursive(Integer value){
  System.out.print(value);
  if (value > 1) {
    mirrorRecursive(value - 1);
  }
  System.out.print(value);

  return value;
}

即递归调用前后打印当前数,递归调用只要value > 1.