当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Print forward sequencing followed by backward sequencing till the beginning?

问题描述:

I have an interesting problem to solve where I have given start and end integer values and I will need to print from start to end and then from end to start using recursion.

for example -

start = 2 and end = 5 then the method should print the following,

2,3,4,5,4,3,2

I can easily do the first part using the code,

public static void countUp(int start, int end) {

System.out.println(start);

if(start< end){

countUp(start+1, end);

}

}

But, then the start value is increased within recursion and I don't have a way to find where to decrease. How can I improve my code mentioning only one method is allowed to use ? Currently, It's only printing

2,3,4,5 // I don't care about the commas

网友答案:

countUp(start+1, end); doesn't increase start - it computes start+1 and passes the result to a new invocation of countUp, which will have its own value of start. Inside the current invocation, start still has the same value. After the recursive call has completed, control will return to the current invocation and will continue after the call. What happens if you simply print start at the end of your method?

网友答案:

try this,

public static void countUp(int start, int end) {    

 System.out.println(start);

  if(start< end){

     countUp(start+1, end);
     System.out.println(start); //backtracking

   }
}
网友答案:

The solution of the problem only with recursion is as following,

public static void countUp(int start, int end) {    

    System.out.println(start);

    if( start< end){

        countUp(start+1, end);
    }

    if( start != end){

        System.out.println(start);
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: