You could always put it into a StringBuffer and reverse it:
import java.util.*;
public class ReverseTest
{
public static void main(String[] args)
{
int reverseThisNumber = 12345678;
StringBuffer sb = new StringBuffer(""+reverseThisNumber);
System.out.println(sb.reverse().toString());
}
}
Or you could use a recursive String reverse method:
public String reverse(String arg)
{
String tmp = null;
if (arg.length() == 1)
{
return arg;
}
else
{
//extract the last char
String lastChar = arg.substring(arg.length()-1,arg.length());
//extract the remaining chars
String remainingString = arg.substring(0, arg.length() -1);
tmp = lastChar + reverse(remainingString);
System.out.println(tmp);
return tmp;
}
}
Then you could go with highergrounds idea and use modulus:
public int revDigits (int num) {
if (num < 10) {
return num;
} else {
int s = num / 10;
int d = num % 10;
int i = revDigits(s);
return (d * 10) + i; // incorrect
// need to find out how many digits in d:
//return (d * 10^(num digits in d)) + i);
}
}
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20