Can somebody help me with this problem? It must use recursion however, and no iterative statements.
Write a method called reverse that takes a single long integer argument and returns the result of reversing its digits.
For example:

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


System.out.print(reverse(1234567)); returns 7654321

i know that (number % 10) gives the last digit and that (number / 10) gives the rest of the number, but i can't put it together. Here's what i got so far:

public static int reverse (int num)
      if(num / 10 == 0)
          return num;
      return (reverse(num%10) * 10 ) + (num / 10);

Edited by pyTony: fixed formatting

11 Years
Discussion Span
Last Post by charlesguo25

public static long reverse(long num)
if(num<10) return num;
int f=((""+num).charAt(0))-48;
long sub=Long.parseLong((""+num).substring(1));
return 10*reverse(sub)+f;

public static long reverse2(long num)
if(num<10) return num;
int f=(int)(num%10);
return Long.parseLong(f+""+reverse(num/10));

Both of those work for positive longs, not sure about negatives.
The first one grabs left hand character and puts to the right, the second does right to left.
Hope that helps

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.