In this post we’ll see how to reverse a number in Java. The Java program to reverse a number can be written in both iterative as well as recursive way. Both solutions are given here.
Logic for both of the method is similar; you need to do a modulo division by 10 to get the last digit and using that remainder you need to create the reversed number. In iterative method this will be done in a loop where as in a recursive method you will call the method again after removing the last digit.
Java code to reverse a number – Iterative and Recursive
public class ReverseNumber { public static void main(String[] args) { int reverseNum = numberReverse(145); System.out.println("Reversed number is " +reverseNum); System.out.println("------------------"); reverseNum = numberReverseRecursive(1997, 0); System.out.println("Reversed number is (recursive) " +reverseNum); } private static int numberReverse(int number){ int reverseNum = 0; int remainder; while (number > 0) { remainder = number % 10; reverseNum = (reverseNum * 10) + remainder; number = number / 10; } return reverseNum; } // recursive method private static int numberReverseRecursive(int number, int reverse){ if (number != 0){ reverse = reverse * 10 + (number % 10); // calling method again return numberReverseRecursive(number/10, reverse); }else{ return reverse; } } }Output
Reversed number is 541 ------------------ Reversed number is (recursive) 7991
That's all for the topic How to Reverse a Number in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like
No comments:
Post a Comment