Wednesday, June 26, 2013

Reversing an Integer

Often, while learning to code in any language (including Java), we come across questions that ask you to reverse an integer. For beginners, it may seem to be a very difficult problem to solve, but actually there is a trick that makes it really easy. The trick is to keep on finding the remainder of the number by dividing it with 10 to extract the digits, and also divide the integer by 10 to reduce it till it doesn't equals zero.
Below is the code written in Java that will give you a better idea:

import java.io.*;
class Reverse{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int num, rev=0, rem;
System.out.print("Enter the integer:");
num=Integer.parseInt(br.readLine());
while(num!=0){
rem=num%10;
rev=rev*10+rem;
num/=10;
}
System.out.println(rev);
}
}

No comments:

Post a Comment