abysmaldan - 1 year ago 62

Java Question

I have been trying this for some time now but could not get it to work. I am trying to have a method to reverse an integer without the use of strings or arrays. For example, 123 should reverse to 321 in integer form.

My first attempt:

`/** reverses digits of integer using recursion */`

public int RevDigs(int input)

{

int reverse = 0;

if(input == 0)

{

return reverse;

}

int tempRev = RevDigs(input/10);

if(tempRev >= 10)

reverse = input%10 * (int)Math.pow(tempRev/10, 2) + tempRev;

if(tempRev <10 && tempRev >0)

reverse = input%10*10 + tempRev;

if(tempRev == 0)

reverse = input%10;

return reverse;

}//======================

I also tried to use this, but it seems to mess up middle digits:

`/** reverses digits of integer using recursion */`

public int RevDigs(int input)

{

int reverse = 0;

if(input == 0)

{

return reverse;

}

if(RevDigs(input/10) == 0)

reverse = input % 10;

else

{

if(RevDigs(input/10) < 10)

reverse = (input % 10) *10 + RevDigs(input/10);

else

reverse = (input % 10)* 10 * (RevDigs(input/10)/10 + 1) + RevDigs(input/10);

}

return reverse;

}

I have tried looking at some examples on the site, however I could not get them to work properly. To further clarify, I cannot use a String, or array for this project, and must use recursion. Could someone please help me to fix the problem. Thank you.

Answer Source

What about:

```
public int RevDigs(int input) {
if(input < 10) {
return input;
}
else {
return (input % 10) * (int) Math.pow(10, (int) Math.log10(input)) + RevDigs(input/10);
/* here we:
- take last digit of input
- multiply by an adequate power of ten
(to set this digit in a "right place" of result)
- add input without last digit, reversed
*/
}
}
```

This assumes `input >= 0`

, of course.