Skip to main content

Java Problem 06 | Reverse an Integer

In this coding tutorial, we break down a complete Java solution for reversing an integer – a common interview question from companies like Google, Amazon, and Facebook. We'll handle edge cases, avoid integer overflow, and write clean, efficient code.
📌 What You'll Learn:
✅ How to reverse digits of an integer mathematically
✅ Why using long prevents integer overflow
✅ How to handle negative numbers correctly
✅ Proper bounds checking with Integer.MAX_VALUE and Integer.MIN_VALUE
✅ Step-by-step debugging of the reversal process
⚠️ Important Edge Cases Covered:
  • Input: 123 → Output: 321
  • Input: -456 → Output: -654
  • Input: 1534236469 → Output: 0 (overflow case!)
  • Input: -2147483648 → Special MIN_VALUE handling
  • Input: 0 → Output: 0
📚 Perfect For:
  • Java beginners learning algorithm fundamentals
  • Coding interview preparation
  • Computer science students
  • Developers practicing LeetCode/HackerRank problems
public class ReverseInteger {
	// Main method to test the reverse function
	public static void main(String[] args) {
		System.out.println(reverseInt(123)); // Output: 321
	}
	
	// Reverses an integer; returns 0 if reversed value overflows
	static int reverseInt(int n) {
		if (n == 0) return 0; // Handle zero directly
		
		final int iMax = Integer.MAX_VALUE; // Max integer value
		final int iMin = Integer.MIN_VALUE; // Min integer value
		int d = Math.abs(n); // Work with absolute value for reversal
		long r = 0; // Use long to detect overflow
		
		if (n >= iMin || n <= iMax) { // Always true for valid int
			for (int i = d; i > 0; i /= 10) { // Process each digit
				r = r * 10 + (i % 10); // Append next digit
				if ( r > iMax || r < iMin) { // Check overflow
					return 0;
				}
			}
		}
		
		if (n < 0) { // Restore original sign
			return -(int) r;
		}
		return (int) r;
	}
}


👍 Like this video if you found it helpful!
🔔 Subscribe for more coding tutorials and interview prep content!
💬 Questions? Drop them in the comments below!
#Java #Programming #CodingInterview #LeetCode #Algorithm #ReverseInteger #JavaTutorial #SoftwareEngineering #ComputerScience #OverflowHandling

Comments

Popular posts from this blog

How to fix MOV files not playing on Windows 10 or 11

How to TEST KEYBOARDS on PC or Laptop

Apple CONFIRMS iPhone 17 Pro Max Camera Noise Bug - Fix Coming?