Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Recursion help

1. ## Recursion help

Hello, im new the forums and was wondering if you could help me with a problem I have to do for my Comp Sci class.

The question is:

Write a function called reverse that takes a long integer argument and returns the result of reversing its digits.

for example System.out.print(reverse(-12); returns -21

Im not just asking for someone to spew out the code but also if they had the time to also possibly explain it a little more for me?

any help is appreciated thank you.

2. ## Re: Recursion help

Probably more than one way to do it (there always is), but I'll hint towards one way. First, think String. Second, think reverse the String.

3. ## Re: Recursion help

Here's some tips that hopefully should help you figure it out:

Recursion is just breaking up a big problem into smaller pieces. What pieces can you break the problem up into (hint, see copeg's post)?

Once you reach the smallest possible piece, you simply tell the program that there is a certain solution for that problem. The program will then "back-track" up and build up the final solution once it knows the solution of all the smaller problems.

Ex:

123456

123456 reversed, it should end in 1. So, just need to reverse 23456 and put that in front of the 1.

23456 reversed, it should end in 2. So, just need to reverse 3456 and put that in front of the 2.

...

6 reversed is known (it is 6). Know the solution to this base case, now just put the final answer together.

4. ## Re: Recursion help

so this is what i came up with i think it will work.
```public static void Long(Long n){
System.out.prinln(n % 10);
if(n / 10 !=0)
reverse(n/10);

}```

5. ## Re: Recursion help

Remember, you have to do it in reverse:
```public static void Long(long n)
{
if (n / 10 != 0)
{
reverse(n/10);
}
System.out.println(n%10);
}```