I can successfully reverse an integer (1234 becomes 4321) with a recursive method that just prints to the console. However, I am having trouble with what I really need it to do: return the reversed int as an int.

Can anybody help me out?

# Recursively reversing an int in java

Started by
npsken
, Oct 19 2009 06:13 PM

4 replies to this topic

### #1

Posted 19 October 2009 - 06:13 PM

### #2

Posted 19 October 2009 - 09:35 PM

Lol, i had to do this during an interview to get a job (not laughing at you, just find it funny that it would come up again).

Do you have to do it recursively, or can you use an iterative approach? Could you provide the code you have (it's easier to tweak than to re-invent)?

Do you have to do it recursively, or can you use an iterative approach? Could you provide the code you have (it's easier to tweak than to re-invent)?

**Edited by rc69, 19 October 2009 - 09:35 PM.**

### #3

Posted 20 October 2009 - 05:57 AM

No looping allowed.

I would post the code I have but it's been mangled to such a form that it can't be read by anything. I've thought of some new methods in my head that I'll try though.

If anybody has any ideas or even pseudo code that could help me out that would be greatly appreciated.

I have found a solution that works. It's not very efficient as far as I can tell, and you guys can probably come up with something better. Here it is:

It basically converts the int to a String which is reversed and then turned back into an int which is returned.

Any thoughts?

I would post the code I have but it's been mangled to such a form that it can't be read by anything. I've thought of some new methods in my head that I'll try though.

If anybody has any ideas or even pseudo code that could help me out that would be greatly appreciated.

**EDIT:**I have found a solution that works. It's not very efficient as far as I can tell, and you guys can probably come up with something better. Here it is:

import java.util.Scanner;public class MyRecursion { private static String reverseDigits(String num) { String temp = null; if (num.length() == 1) { return num; } else { String lastChar = num.substring(num.length() - 1, num.length()); String remainingString = num.substring(0, num.length() - 1); temp = lastChar + reverseDigits(remainingString); return temp; } } public static int reverseDigits(int num) { String temp = "" + num; return Integer.parseInt(reverseDigits(temp)); } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); int num = in.nextInt(); System.out.println(num + " in reverse is " + reverseDigits(num) + "."); }}

It basically converts the int to a String which is reversed and then turned back into an int which is returned.

Any thoughts?

**Edited by npsken, 20 October 2009 - 08:31 AM.**

### #4

Posted 20 October 2009 - 11:15 PM

Well, I don't know Java, but I can give you an idea I came up with in psudo-code. Something I forgot about when I was doing C++ and manipulating numbers, is you can use

In this case, what you can do, is pick off the ending number of your original number, and stick it onto the front your new number. This may look something like this (in C++).

How this works is the modulus will find the remainder of the number divided by ten. So in the example, it would be 1234/10, remainder is that 4. Then, we subtract that number from the original, making this 1234-4=1230. Dividing this by ten will make it reduced by one place, 1230/10=123, making it ready for the next iteration to be broken down again. Then, we take that remainder to build our new number by taking our new number, which at this point is just 0, and multiplying by ten to add a new place value. Adding the remainder number puts it on the end, 0+4=4. Now on the second iteration of the loop, as this will repeat until our original number is not able to be divided again, will make it 123%10=3, (123-3)/10=12, 4*10+3=43.

I've just tested this with JavaScript in a console and it works how you'd want it.

Oh, I just got this all typed and realized you said no looping allowed... may I ask why? Recursion seems redundant in this case and totally un-necessary...

Oh well, should atleast show you that you can use math to get this accomplished and be able to tweak it to return an int like you want.

*math*to manipulate numbers, rather than string operations.In this case, what you can do, is pick off the ending number of your original number, and stick it onto the front your new number. This may look something like this (in C++).

int myNumber = 1234; int newNumber = 0; int numberTemp = 0; while(myNumber > 0){ // Cut the last number off using modulus (remainder after division) numberTemp = myNumber % 10; // Take that our of our number for the next iteration myNumber = (myNumber - numberTemp) / 10; // Multiply it into our new number newNumber = newNumber * 10 + numberTemp; }

How this works is the modulus will find the remainder of the number divided by ten. So in the example, it would be 1234/10, remainder is that 4. Then, we subtract that number from the original, making this 1234-4=1230. Dividing this by ten will make it reduced by one place, 1230/10=123, making it ready for the next iteration to be broken down again. Then, we take that remainder to build our new number by taking our new number, which at this point is just 0, and multiplying by ten to add a new place value. Adding the remainder number puts it on the end, 0+4=4. Now on the second iteration of the loop, as this will repeat until our original number is not able to be divided again, will make it 123%10=3, (123-3)/10=12, 4*10+3=43.

I've just tested this with JavaScript in a console and it works how you'd want it.

Oh, I just got this all typed and realized you said no looping allowed... may I ask why? Recursion seems redundant in this case and totally un-necessary...

Oh well, should atleast show you that you can use math to get this accomplished and be able to tweak it to return an int like you want.

### #5

Posted 23 October 2009 - 10:34 AM

Even though i'm against helping with homework, i'm posting this here just because of how cool it is. It is infinitely more elegant than the solution i came up with during the interview (thank you demonslay for the idea).

public class test{ private static int depth = 0; private static int reverse(int num){ if(num < 1){ return 0; } int temp = num % 10; num = (num - temp)/10; return reverse(num) + (int)(temp * Math.pow(10,depth++)); } public static void main(String[] args){ System.out.println(reverse(1)); depth = 0; System.out.println(reverse(12)); depth = 0; System.out.println(reverse(1234)); depth = 0; System.out.println(reverse(1234000)); } }Note: If you care about trailing zeros, stick with the string-based solution.

#### 1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users