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

and

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);
  }

Recommended Answers

All 2 Replies

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

Thank you very much. It works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.