Reverse the Number in Java
Here, you will get the program code to Reverse the Number in Java programming.
Reverse a number is a mathematical operation in which the digits of a given number are reversed to create a new number.
For example, if the number is 2345, then the reverse of that number would be 5432.
Reverse the Number in Java using For Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.util.Scanner; class ReverseTheNumber { public static void main(String...s) { int reversenum = 0, num, num1, i, sum=0; Scanner sc=new Scanner(System.in); System.out.println("Enter a number:"); num = sc.nextInt(); num1 = num; for(;num!=0;) { i=num%10; reversenum = reversenum * 10 + i; num/=10; } System.out.println("Reverse Number of " + num1 + " is = " + reversenum); } } |
Output
Reverse Number in Java using While loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //Reverse of a Number in Java import java.util.Scanner; class ReverseTheNumber { public static void main(String...s) { int reversenum = 0, num, num1, i, sum=0; Scanner sc=new Scanner(System.in); System.out.println("Enter a number:"); num = sc.nextInt(); num1 = num; while(num!=0) { i=num%10; reversenum = reversenum * 10 + i; num/=10; } System.out.println("Reverse Number of " + num1 + " is = " + reversenum); } } |
Output
C:\CodeRevise\java>javac ReverseTheNumber.java
C:\CodeRevise\java>java ReverseTheNumber
Enter a number:
10976
Reverse Number of 10976 is = 67901
Reverse Number in Java without Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Scanner; public class ReverseNumWithoutLoop{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter a number:"); int num = sc.nextInt(); // Convert number to string String numtoStr = Integer.toString(num); // Reverse the string String revStr = new StringBuilder(numtoStr).reverse().toString(); // Convert string to integer int revNum = Integer.parseInt(revStr); // Print the reversed number System.out.println("Original Number: " + num); System.out.println("Reversed Number: " + revNum); } } |
Output
C:\CodeRevise\java>javac ReverseNumWithoutLoop.java
C:\CodeRevise\java>java ReverseNumWithoutLoop
Enter a number:
2345
Original Number: 2345
Reversed Number: 5432
Check out our other Java Programming Examples