BLOGGER TEMPLATES AND TWITTER BACKGROUNDS

25 January, 2011

Java: Reverse a number

This program will reverse a long and store it in another.

class NumRev
{
public static void main(String ar[])
{
long num = 1357912; /* Try with diff values */
long rev = 0;
int i = (((Long)num).toString()).length(); /* No of digits */


System.out.println("Original Number: " + num);
for(i-=1; num!=0; i--)
{
long rem = num % 10;
rev += (rem * Math.pow(10, i));
num /= 10;
}


System.out.println("Reversed Number: " + rev);
}
}


Difficulty Rating: 2.5/10
For creative minds: This program gets the number of digits in a number by converting it to a string. Can you do it without the string portion? Is it possible to reverse without using the number of digits at all?