Reverse Integer without converting into a String
Sangeethraj
Posted on April 1, 2022
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));
}
}
Output :
Before Swap: 4567
After Swap: 7654
Steps :
- Create a revNumber() method returning int
- Declare the return variable and initialize with 0
- Create for loop to iterate until the user input becomes zero
- Assign value to return variable use Modulo or Remainder Operator in Java add to declared return variable
- Assign value to input variable divide Operator in Java
- Return the declared variable
- Declare the input in main method
- 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❤️❤️❤️
Posted on April 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.