Reversing a number means that the digit at the first position should be swapped with the last digit, the second digit will be swapped with the second last digit, and so on till the middle element,
To reverse a number following steps should be performed:
- Take the number’s modulo by 10
- Multiply the reverse number by 10 and add modulo value into the reverse number.
- Divide the number by 10.
- Repeat above steps until number becomes zero.
We can reverse a number in java using two methods.
1. Using While Loop:
Simply apply the steps/algorithm discussed and terminate the loop when the number becomes zero.
- Take the number’s modulo by 10
- Multiply the reverse number by 10 and add modulo value into the reverse number.
- Divide the number by 10.
- Repeat the above steps until the number becomes zero.
Below is the implementation of the above approach:
Java
// Java program to reverse a number import java.io.*; class GFG { // Function to reverse the number static int reverse( int n){ int rev = 0 ; // reversed number int rem; // remainder while (n> 0 ){ rem = n% 10 ; rev = (rev* 10 ) + rem; n = n/ 10 ; } return rev; } // Driver Function public static void main (String[] args) { int n = 4526 ; System.out.print( "Reversed Number is " + reverse(n)); } } |
Reversed Number is 6254
2. Using Recursion:
In recursion, the final reverse value will be stored in the global ‘rev’ variable. Follow the below instructions.
- If the number becomes zero then terminate the recursion, this will be the base condition.
- Take the modulo and add it with the ‘rev*10’ multiplying.
- Divide the number by 10 and call the reverse function on this number after updating it to number/10.
Below is the Java implementation of the recursion method.
Java
// Java program to reverse a number recursively import java.io.*; class GFG { // stores reversed number static int rev = 0 ; // Function to reverse the number static void reverse( int n){ if (n<= 0 ) return ; int rem = n% 10 ; // remainder rev = (rev* 10 ) + rem; reverse(n/ 10 ); } // Driver Function public static void main (String[] args) { int n = 4526 ; reverse(n); System.out.print( "Reversed Number is " + rev); } } |
Reversed Number is 6254
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.