Java Examples

Java Program - Reverse digits of a given Integer



In Java, the reverse of a given integer can be found out by using below mentioned methods.

Method 1: Using iteration

The method involves the following steps:

Input: MyNum
Step 1: Initialize the RevNum = 0
Step 2: Iterate over MyNum while it is greater than zero.
   Step 2a: Calculate remainder of MuNum / 10
   Step 2b: Update RevNum by RevNum * 10 + remainder
   Step 2c: Update MyNum by MyNum / 10
Step 3: Return RevNum

Example:

Input: 564

RevNum: 0
Iteration 1: 
    Remainder: 564 % 10 = 4
    RevNum: 0 * 10 + 4 = 4
    MyNum: 564 / 10 = 56

Iteration 2: 
    Remainder: 56 % 10 = 6
    RevNum: 4 * 10 + 6 = 46
    MyNum: 56 / 10 = 5

Iteration 3: 
    Remainder: 5 % 10 = 5
    RevNum: 46 * 10 + 5 = 465
    MyNum: 5 / 10 = 0

return RevNum = 465

The below block of code shows the implementation of above concept:

public class MyClass {

  static int reverse(int MyNum) {   
    int RevNum = 0;
    int remainder;
    
    while(MyNum > 0){
      remainder = MyNum % 10;
      MyNum = MyNum / 10;
      RevNum = RevNum * 10 + remainder;
    }
    return RevNum;
  }
  
  public static void main(String[] args) {
    int x = 1285;
    int y = 4567;
    System.out.println("Reverse of " + x + " is: " + reverse(x));
    System.out.println("Reverse of " + y + " is: " + reverse(y));
  }
}

The above code will give the following output:

Reverse of 1285 is: 5821
Reverse of 4567 is: 7654

Method 2: Using Recursion

The above result can also be achieved using recursive method. Consider the example below:

public class MyClass {  
  static int RevNum = 0;
  static int base = 1;

  static int reverse(int MyNum) {
    if(MyNum > 0){
      reverse(MyNum/10);
      RevNum += MyNum % 10 * base;
      base *= 10;
    }
    return RevNum;
  }
  
  public static void main(String[] args) {
    int x = 7902;
    System.out.println("Reverse of " + x + " is: " + reverse(x));
  }
}

The above code will give the following output:

Reverse of 7902 is: 2097