How to reverse a number in Java without using any API is asked in many interviews in order to check the logic. Though how to reverse a string is applicable for numbers also by treating them as String but the point here is to have a number and then reverse it without any using any in-built method.
It can be done in two ways
- By iterating and using mathematical operators like divide and multiply.
- Using recursive function.
When iterating through each digit of the number idea is to divide the given number by 10 and adding that remainder to an integer (which is initially initialized to 0) and multiplied by 10 in each iteration. That is required to move place values in the reversed number. Also divide the original number by 10 to get the quotient.
As example– If original number is 189 then first iteration will give remainder as 9 and quotient as 18. In the second iteration remainder will be 8 and quotient 1. And every time it is also multiplied by 10 for place value. Thus after second iteration it will be (9 * 10) + 8 = 98. Same for third iteration where remainder will be 1 and quotient 0. Thus making it (98 * 10) + 1 = 981. Which is the reversed number.
In recursive method you call the same method with one less digit that is done by dividing the number by 10. You have to print modulo division in every recursive call. Using recursion this way will also print the zeroes which the other way of iteration will not do. Meaning using the first method will give you 2 if input is 200. Whereas recursive method will give 002.
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
System.out.println("Please enter a number : ");
Scanner sc = new Scanner(System.in);
int scanInput = sc.nextInt();
// Using recursion
reverseRec(scanInput);
// Using while loop
reverseNum(scanInput);
}
// Method for reversing number using recursion
public static void reverseRec(int num){
//System.out.println("num" + num);
if(num == 0)
return;
System.out.print(num % 10);
reverseRec(num/10);
}
// Method for reversing number
public static void reverseNum(int num){
int reversedNum = 0;
int mod = 0;
while(num != 0){
mod = num % 10;
reversedNum = (reversedNum * 10) + mod;
num = num/10;
}
System.out.println("reversedNum -- " + reversedNum);
}
}
That's all for this topic How to reverse number - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -