# Recursion help

• January 6th, 2010, 07:19 PM
rhoruns
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.
• January 6th, 2010, 09:36 PM
copeg
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.
• January 7th, 2010, 02:05 AM
helloworld922
Re: Recursion help

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.
• January 7th, 2010, 08:51 PM
rhoruns
Re: Recursion help
so this is what i came up with i think it will work.
Code :

```public static void Long(Long n){ System.out.prinln(n % 10); if(n / 10 !=0) reverse(n/10);   }```
• January 8th, 2010, 10:50 PM
helloworld922
Re: Recursion help
Remember, you have to do it in reverse:
Code :

```public static void Long(long n) { if (n / 10 != 0) { reverse(n/10); } System.out.println(n%10); }```