DEV Community

Sangeethraj
Sangeethraj

Posted on

Reverse Integer without converting into a String

Explanation :
Everyone is familiar with String reverse by when it comes to Integer we must go foe a different technique using Java operators. Here in the method will initialize the return with zero, then create a while loop to iterate until the user input becomes zero, within the loop we will assign value to return variable use Modulo or Remainder Operator by 10 to get only one reminder at the end and store it in in the return variable by adding the answer. After that divide the user input by 10 using Divide Operator so the last value in the Integer will be remove and assign value to input variable. Finally once the user input becomes 0 the loop will stop iteration and return the reversed value. We can call the created method in the main using print statement.

Code :

public class revNum {

    public static int revNumber(int num) {
        /* Declare the return variable*/
        int ans = 0;

        /* Loop to iterate until the int becomes zero*/
        while (num > 0) {
            /* assign value to return variable
               use Modulo or Remainder Operator in Java
               add to declared return variable */
            ans = ans * 10 + num % 10;

            /* assign value to input variable
               Divide Operator in Java */
            num = num / 10;
        }
               /*return the declared variable*/
        return ans;
    }

    public static void main(String[] args) {
        /* Declare the input*/
        int num = 4567;

        /* Call the revNumber method */
        System.out.println("Before Swap: "+num+"\nAfter Swap: "+ revNumber(num));
    }

}
Enter fullscreen mode Exit fullscreen mode

Output :
Before Swap: 4567
After Swap: 7654

Steps :

  1. Create a revNumber() method returning int
  2. Declare the return variable and initialize with 0
  3. Create for loop to iterate until the user input becomes zero
  4. Assign value to return variable use Modulo or Remainder Operator in Java add to declared return variable
  5. Assign value to input variable divide Operator in Java
  6. Return the declared variable
  7. Declare the input in main method
  8. Call the revNumber() method in the print statement

Special Note: The reverse function is familiar to you but when it comes to integer we must special logic, this is how you can optimize code without a reverse function to reverse integer. Hope this will help someone in future!! I welcome your feedback and solutions-oriented suggestions, thank you for your time.

Happy Coding❤️❤️❤️

Top comments (0)