我对这段代码很困惑,分配很简单:“给定一个数字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
就进行递归调用。
关于java - 如何在java中使用递归反转数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59629583/