Introduction
Reversing an integer without converting it into a String is a common Java coding interview problem. The goal is to reverse the order of the digits using arithmetic operations instead of String methods.
For example, reversing the integer 12345 produces 54321. Similarly, reversing 1200 produces 21 because leading zeros are not preserved in an integer.
This problem helps you practice loops, modulo operations, integer division, and numeric data types. It also introduces an important challenge: the reversed number may exceed the range of a Java int, even when the original number fits within that range.
In this tutorial, I will demonstrate how to reverse an integer using arithmetic operations. I will explain the algorithm step by step, show how to handle negative numbers and trailing zeros, and demonstrate two ways to detect integer overflow safely.
1. Understanding Integer Reversal in Java
Integer reversal means rearranging the digits of a number in the opposite order.
Consider the following input:
12345
The expected result is:
54321
The reversal operation processes the digits from right to left.
| Step | Extracted Digit | Reversed Number |
|---|---|---|
| 1 | 5 | 5 |
| 2 | 4 | 54 |
| 3 | 3 | 543 |
| 4 | 2 | 5432 |
| 5 | 1 | 54321 |
The algorithm uses two arithmetic operations:
- The modulo operator
%extracts the last digit. - Integer division by 10 removes the last digit.
Each extracted digit is added to the reversed number after multiplying the existing result by 10.
2. Reverse an Integer in Java Using Modulo and Division
The simplest approach uses a while loop with the modulo and division operators.
For each iteration, the program performs three operations:
- Extract the last digit using
number % 10. - Append the digit using
reversed * 10 + digit. - Remove the last digit using
number / 10.
The process continues until the remaining number becomes zero.
In this example, I will use a long variable for the intermediate result. This allows the program to detect whether the reversed value exceeds the Java int range before returning it.
Java Program Using a While Loop
public class ReverseInteger {
public static void main(String[] args) {
int number = 12345;
int reversed = reverseNumber(number);
System.out.println("Original Number: " + number);
System.out.println("Reversed Number: " + reversed);
}
/**
* Reverses an integer using arithmetic operations.
*
* @param number the integer to reverse
* @return the reversed integer
* @throws ArithmeticException if the result exceeds int range
*/
public static int reverseNumber(int number) {
long reversed = 0;
// Process digits until the number becomes zero.
while (number != 0) {
// Extract the last digit.
int digit = number % 10;
// Append the digit to the reversed number.
reversed = reversed * 10 + digit;
// Remove the last digit.
number /= 10;
}
// Verify that the result fits in a signed int.
if (reversed > Integer.MAX_VALUE
|| reversed < Integer.MIN_VALUE) {
throw new ArithmeticException(
"Reversed number exceeds integer range"
);
}
return (int) reversed;
}
}
Output
Original Number: 12345
Reversed Number: 54321
How Does the Program Work?
Step 1: Initialize the Reversed Number
long reversed = 0;
The program initializes the reversed number to zero.
The long type is used for intermediate calculations because reversing a valid int can produce a value outside the signed 32-bit integer range.
Step 2: Extract the Last Digit
int digit = number % 10;
The modulo operator % returns the remainder after division.
When an integer is divided by 10, the remainder gives its last digit, including its sign for negative inputs.
For example:
12345 % 10 = 5
1234 % 10 = 4
123 % 10 = 3
Step 3: Append the Digit to the Result
reversed = reversed * 10 + digit;
Multiplying the current result by 10 shifts its decimal digits one position to the left.
The extracted digit is then added at the rightmost position.
For example, if the current reversed number is 54 and the next extracted digit is 3:
54 * 10 + 3 = 543
Step 4: Remove the Last Digit
number /= 10;
Integer division by 10 removes the last digit because Java truncates integer division toward zero.
For example:
12345 / 10 = 1234
1234 / 10 = 123
123 / 10 = 12
12 / 10 = 1
1 / 10 = 0
When the number becomes zero, the loop terminates.
Step 5: Check for Integer Overflow
if (reversed > Integer.MAX_VALUE
|| reversed < Integer.MIN_VALUE) {
throw new ArithmeticException(
"Reversed number exceeds integer range"
);
}
A Java int supports values from -2,147,483,648 to 2,147,483,647.
If the reversed result exceeds this range, the method throws an ArithmeticException.
Otherwise, the result is safely converted to int.
When should you use this approach?
The arithmetic loop is a good choice for beginners and coding interviews. It avoids String conversion, processes one digit at a time, and handles both positive and negative integers.
3. Reverse an Integer Using Math.multiplyExact() and Math.addExact()
You can also reverse an integer using exact arithmetic methods provided by Java.
The Math.multiplyExact() and Math.addExact() methods throw an ArithmeticException when an operation overflows the integer range.
This allows the program to detect overflow without using a wider numeric type.
Java Program Using Exact Arithmetic
public class ReverseIntegerUsingExactMath {
public static void main(String[] args) {
int number = -12340;
try {
int reversed = reverseNumber(number);
System.out.println("Original Number: " + number);
System.out.println("Reversed Number: " + reversed);
} catch (ArithmeticException exception) {
System.out.println("Unable to reverse the number: "
+ exception.getMessage());
}
}
/**
* Reverses an integer using exact arithmetic operations.
*
* @param number the integer to reverse
* @return the reversed integer
* @throws ArithmeticException if an intermediate result overflows
*/
public static int reverseNumber(int number) {
int reversed = 0;
while (number != 0) {
int digit = number % 10;
// Detect overflow during multiplication and addition.
reversed = Math.addExact(
Math.multiplyExact(reversed, 10),
digit
);
number /= 10;
}
return reversed;
}
}
Output
Original Number: -12340
Reversed Number: -4321
Explanation
The program follows the same digit-reversal algorithm as the first example.
The difference is how it handles arithmetic:
reversed = Math.addExact(
Math.multiplyExact(reversed, 10),
digit
);
The Math.multiplyExact() method multiplies the current result by 10.
The Math.addExact() method adds the extracted digit.
If either operation exceeds the signed int range, Java throws an ArithmeticException.
This is preferable to allowing silent integer overflow, which can produce an incorrect result.
Why Does the Negative Sign Remain Correct?
Java's remainder operator preserves the sign of the dividend.
For example:
-123 % 10 = -3
As a result, the reversed digits remain negative during the calculation.
The program does not need to remove the sign and add it again.
When should you use this approach?
Use this approach when you want to demonstrate safe integer arithmetic and explicit overflow detection.
It also provides a good example of how Math.multiplyExact() and Math.addExact() can prevent silent arithmetic errors.
4. Reverse an Integer with Trailing Zeros
One important edge case is an integer that ends with one or more zeros.
For example:
Input: 1200
Reversed: 21
When the program processes 1200, it extracts the digits in this order:
0, 0, 2, 1
The intermediate calculations are:
0 * 10 + 0 = 0
0 * 10 + 0 = 0
0 * 10 + 2 = 2
2 * 10 + 1 = 21
The leading zeros disappear automatically because an integer does not preserve leading zeros.
No special handling is required.
5. Handling Different Integer Inputs
A reliable integer-reversal program should handle positive numbers, negative numbers, zero, trailing zeros, and overflow.
| Input | Expected Result | Explanation |
|---|---|---|
| 12345 | 54321 | Standard positive integer |
| -123 | -321 | Negative sign is preserved |
| 1200 | 21 | Leading zeros disappear |
| 0 | 0 | No digits to rearrange |
| 7 | 7 | Single-digit number |
| 1534236469 | ArithmeticException | Reversed value exceeds int range |
What Happens When the Input Is Integer.MIN_VALUE?
The smallest Java int is -2,147,483,648.
Reversing its digits would produce -8,463,847,412, which does not fit in a signed int.
Both implementations detect this problem and throw an ArithmeticException.
The first uses a long intermediate result, while the second checks overflow during each arithmetic operation.
6. How to Run the Java Programs
You can run these examples using IntelliJ IDEA, Eclipse, VS Code, or directly from the command line.
Java 17 or later is sufficient. No external dependencies are required.
Step 1: Create a Java File
Create a file named ReverseInteger.java.
Copy the complete code from the first example into the file.
Step 2: Compile the Program
javac ReverseInteger.java
Step 3: Run the Program
java ReverseInteger
The expected output is:
Original Number: 12345
Reversed Number: 54321
To run the second example, save its code in a separate file named ReverseIntegerUsingExactMath.java.
7. Time and Space Complexity
The algorithm processes each decimal digit exactly once.
If the input contains d digits, the loop executes at most d times.
- Time complexity: O(d)
- Auxiliary space complexity: O(1)
Both implementations use only a fixed number of variables.
The first approach uses a long intermediate value, while the second performs checked arithmetic directly with int.
Neither approach creates a String or an array.
8. Common Mistakes When Reversing Integers
1. Using String Conversion When It Is Not Allowed
The problem specifically asks you to reverse an integer using arithmetic operations.
Converting the number using String.valueOf() and reversing the String does not satisfy that requirement.
2. Forgetting to Remove the Last Digit
After extracting a digit, the program must update the remaining number:
number /= 10;
Without this statement, the loop would repeatedly process the same digit.
3. Updating the Reversed Number Incorrectly
The correct calculation is:
reversed = reversed * 10 + digit;
Multiplication by 10 shifts the existing digits so that the next digit can be appended.
4. Ignoring Integer Overflow
The reversed value may exceed the range of a signed Java int.
Without overflow detection, arithmetic may wrap around and produce an incorrect result.
Use a wider intermediate type or Java's exact arithmetic methods.
5. Converting Negative Numbers to Positive Using Math.abs()
Using Math.abs() is unnecessary for this algorithm.
It can also create problems with Integer.MIN_VALUE, whose absolute value cannot be represented as an int.
The arithmetic loop can process negative numbers directly.
6. Expecting Leading Zeros in an Integer
An integer cannot preserve leading zeros.
For example, reversing 1200 produces 21, not 0021.
If leading zeros must be preserved, the data should be treated as text rather than a numeric value.
9. Frequently Asked Questions
How do you reverse an integer in Java without using a String?
Use the modulo operator to extract the last digit, multiply the reversed result by 10, add the digit, and divide the original number by 10. Repeat until the remaining number becomes zero.
Which Java operators are used to reverse a number?
The algorithm primarily uses the modulo operator %, multiplication *, addition +, and integer division /.
Can negative integers be reversed?
Yes. Java's remainder and integer division operators allow the algorithm to process negative integers directly.
For example, -123 becomes -321.
What happens when a number ends with zeros?
Trailing zeros become leading zeros after reversal. Since integer values do not preserve leading zeros, those zeros disappear.
For example, 1200 becomes 21.
What happens if the reversed number exceeds the int range?
The method should handle overflow explicitly.
The examples in this tutorial throw an ArithmeticException rather than returning an incorrect value.
What is the time complexity of reversing an integer?
The algorithm takes O(d) time, where d is the number of decimal digits. It also uses O(1) additional space.
Can an integer be reversed without using an array?
Yes. The arithmetic algorithm uses only a few numeric variables and does not require an array or collection.
Does reversing an integer modify the original variable?
In these examples, the method receives a copy of the primitive int value. Changes to the method parameter do not modify the caller's variable.
Conclusion
In this tutorial, you learned how to reverse an integer in Java without converting it into a String.
The main approach uses the modulo operator to extract digits and integer division to remove processed digits. Each digit is appended to the reversed result using multiplication and addition.
You also learned how to handle negative numbers, trailing zeros, and integer overflow. These details are important because a reversed integer may fall outside the valid range of the int type.
The first implementation uses a long intermediate result to detect overflow. The second uses Math.multiplyExact() and Math.addExact() to catch overflow during arithmetic operations.
For Java coding interviews, I recommend learning the arithmetic loop first. Make sure you understand why % 10 extracts the final digit and why dividing by 10 removes it.
As a next step, try writing a Java program that checks whether an integer is a palindrome without converting it into a String. You can reuse the same digit-reversal algorithm.
Official Java Documentation and References
For more information about the Java APIs and arithmetic operations used in this tutorial, refer to the following official documentation:
-
Java Integer API Documentation – Signed 32-bit integer limits, including
Integer.MIN_VALUEandInteger.MAX_VALUE. - Java Long API Documentation – Signed 64-bit integer values and their supported range.
-
Java Math API Documentation – Exact arithmetic methods such as
multiplyExact()andaddExact(). - Java Language Specification – Expressions – Arithmetic operators, integer division, and remainder operations.
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment