Reverse A Number In Java Leetcode Solution
Reversing a number is a common programming challenge that tests your understanding of basic arithmetic operations and loop structures. This article explores various ways to reverse an integer in Java, similar to problems found on platforms like LeetCode.
Problem Statement
Given an integer, return its reverse. For example, if the input is 123, the output should be 321. If the input is -123, the output should be -321. Consider the case where reversing the number might cause an overflow.
Example
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
Background & Knowledge Prerequisites
To understand the solutions, you should be familiar with:
- Basic Java syntax: Variables, data types (especially
intandlong). - Arithmetic operators: Modulo (
%) for getting the last digit, division (/) for removing the last digit. - Control flow:
whileloops. - Conditional statements:
if-elsefor handling negative numbers and overflow.
Use Cases or Case Studies
Reversing numbers isn't just a theoretical exercise; it has practical applications:
- Palindrome checking: Determining if a number reads the same forwards and backward (e.g., 121).
- Data manipulation: In some algorithms, reversing digits might be a step in transforming data.
- Cryptography: While not directly reversing numbers, digit manipulation is fundamental in many cryptographic algorithms.
- Educational exercises: It's a classic problem for beginners to practice loops and arithmetic.
- Display formatting: Sometimes, numbers need to be displayed in a reversed order for specific UI requirements.
Solution Approaches
We will explore a common and robust approach to reversing an integer, focusing on handling negative numbers and potential overflow.
Approach 1: Iterative Reversal with Overflow Check
This approach uses a while loop to extract digits from the original number and construct the reversed number. It includes crucial checks to prevent integer overflow, which is a common pitfall in such problems.
One-line summary
Iteratively extracts digits using modulo and division, building the reversed number while checking forint overflow.
Code example
// Reverse Integer
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer to reverse: ");
int x = scanner.nextInt();
scanner.close();
int reversedNum = reverse(x);
System.out.println("Reversed number: " + reversedNum);
}
public static int reverse(int x) {
long reversed = 0; // Use long to detect potential overflow before casting to int
while (x != 0) {
int digit = x % 10; // Get the last digit
reversed = reversed * 10 + digit; // Append the digit to the reversed number
x /= 10; // Remove the last digit from the original number
// Check for overflow before the next iteration
// If reversed goes beyond Integer.MAX_VALUE or Integer.MIN_VALUE, it's an overflow
if (reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE) {
return 0; // Return 0 as per LeetCode's common requirement for overflow
}
}
return (int) reversed; // Cast back to int for the final result
}
}
Sample output
Enter an integer to reverse: 123
Reversed number: 321
Enter an integer to reverse: -123
Reversed number: -321
Enter an integer to reverse: 120
Reversed number: 21
Enter an integer to reverse: 2147483647
Reversed number: 0
(Note: 2147483647 is Integer.MAX_VALUE. Reversing it would lead to 7463847412, which overflows int. Hence, 0 is returned.)
Stepwise explanation for clarity
- Initialize
reversed: Alongvariablereversedis initialized to0. We uselonghere to temporarily store the reversed number. This allows us to detect overflow before the value is truncated when cast back toint. - Loop while
xis not zero: Thewhile (x != 0)loop continues as long as there are digits left in the original numberx. - Extract the last digit:
int digit = x % 10;calculates the remainder whenxis divided by 10. This gives us the last digit ofx.
- Example: If
x = 123,digitbecomes3.
- Build the reversed number:
reversed = reversed * 10 + digit;shifts the existingreversednumber one decimal place to the left (multiplying by 10) and then adds the newly extracteddigit.
- Example:
-
reversed = 0,digit = 3->reversed = 0 * 10 + 3 = 3 -
reversed = 3,digit = 2->reversed = 3 * 10 + 2 = 32 -
reversed = 32,digit = 1->reversed = 32 * 10 + 1 = 321
- Remove the last digit from
x:x /= 10;performs integer division ofxby 10, effectively removing its last digit.
- Example: If
x = 123,xbecomes12. Then1. Then0.
- Check for overflow: Inside the loop, after updating
reversed, we checkif (reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE). Ifreversedexceeds the maximum or minimum value anintcan hold, it means an overflow would occur if we cast it toint. In such cases, the function returns0as specified by many problem statements (e.g., LeetCode). - Return the result: Once the loop finishes (when
xbecomes `0