Reverse of number in java (3 approaches)
Here you can learn how to reverse a number in java programming language with 3 different approaches.
Approach:-1 "reverse number in java using for loop"
import java.util.Scanner;
public class usingForLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = sc.nextInt();
int revNum = 0;
for(int i = 0; i <= num; i++){
int lastDigit = num % 10;
revNum = revNum * 10 + lastDigit;
num = num / 10;
}
System.out.println("The reverse number is: "+revNum);
}
}
Output
Approach:-2 "find reverse of a number in java using while loop"
import java.util.Scanner;
public class usingWhileLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = sc.nextInt();
int revNum = 0;
while(num != 0){
int lastDigit = num % 10;
revNum = revNum * 10 + lastDigit;
num = num /10;
}
System.out.println("The reverse number is: "+revNum);
}
}
Approach:-3 "reverse a number in java using method"
public class usingMethod {
public static void main(String[] args){
revNumber rv = new revNumber();
int result = rv.findRevNum(468);
System.out.println("The reverse number is: "+result);
}
}
class revNumber{
public int findRevNum(int num){
int revNum = 0;
for(int i = 0; i <= num; i++){
revNum = revNum * 10 + num % 10;
num = num / 10;
}
return revNum;
}
}
Code Explanation
I will properly explain these above 3 approaches that we can use to find the reverse number in java.
Approach:-1
- Here num % 10 will provide the last digit of a number. We have stored it on lastDigit variable.
- Our task is to keep that last digit in the first, so we have use revNum = revNum * 10 + lastDigit
- Now we have to access the 2nd last digit, so we remove the last number by num / 10.
- Now the same process will continue till the first digit of the number and finally the reverse form of that number will store in the revNum variable.
Approach:-2
- In while loop the concept will remain same, only we have use while loop in the place of for loop.
Approach:-3
- In this approach I haven't taken user input. I have assigned a number to num variable.
- Now I have created a another class i.e revNumber. Inside that class, I have declared a method named findRevNum and inside that method I have written the logic (logic will remain same)
- Now in the main method, I have to create a object to the class revNumber and by using that object I can able to call the method findRevNum.
- If you learn something new from this article please share with your friends.
- If you face any problem and if you have any questions please write it down on the comment below 👇.