Share on Google+Share on Google+

Java reverse number

Advertisement
In this tutorial, you will learn how to reverse a number in java.

Java reverse number

In this tutorial, you will learn how to reverse a number in java.

In java, you can use arithmetic operators like division operator(/) and remainder operator(%) to reverse the number. The division operator returns quotient while modulus or remainder operator % returns remainder. There is no need to use any java api.

Example
import java.util.*;

public class ReverseNumber{
public static void main(String [] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter number: ");
int num= input.nextInt();
int n = num;
int rev=0;
for(int i=0; i<=num; i++){
int r=num%10;
num=num/10;
rev=rev*10+r;
i=0;
}
System.out.println("Reversed Number: "+ rev); 
}
}  

Description of Code:In this example, we have allowed the user to enter the number and reverse it by using basic programming concepts like loops and operators. After each iteration, we have got the number with one digit less than the original number and the variable used to store the reversed number, got that last digit as its first digit. The multiplication of 10 is used to move places in decimal numbers.

Output:

Enter number: 242445
Reversed Number: 544242

Advertisements

Posted on: September 22, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.