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

Sim*_*one 0 java recursion numbers sequence

我很坚持这段代码,赋值很简单:“给定一个数字 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;
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

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

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

  return value;
}
Run Code Online (Sandbox Code Playgroud)

即在递归调用之前和之后打印当前数字,并且只要value>进行递归调用1

  • 这就是答案,但我不认为在 stackoverflow 中我们应该解决家庭作业;-) 作为一种改进,该方法可以无效。 (2认同)