In this post, we will see how to reverse a number in java.
Here is simple program to reverse a number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog; import java.util.Scanner; public class ReverseNumberMain { public static void main(String[] args) { int number, reversedNumber=0, remainder; Scanner scan = new Scanner(System.in); System.out.print("Enter a Number : "); number = scan.nextInt(); while(number != 0) { remainder = number%10; reversedNumber = reversedNumber*10 + remainder; number = number/10; } System.out.print("Reverse of the number : " +reversedNumber); scan.close(); } } |
Output:
Enter a Number : 4567
Reverse of the number : 7654
Reverse of the number : 7654
Let’s just observe values of variables at the end of each iteration.
Iteration 0: number = 4567,remainder = 0, reversedNumber = 0
Iteration 1: number = 456,remainder = 7, reversedNumber = 7
Iteration 2: number = 45,remainder = 6, reversedNumber = 76
Iteration 3: number = 4,remainder = 5, reversedNumber = 765
Iteration 4: number = 0,remainder = 4, reversedNumber = 7654
That’s all about reversing a number in java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.