How to convert string to integer in Java with edge cases

🔹 Day 62 of #100DaysOfLeetCodeChallenge 🔹 🚀 Problem: String to Integer (atoi) 🔑 Topic: String Manipulation 🧠 Approach: Step 1: Trim leading whitespaces. Step 2: Check for a sign (+ or -). Step 3: Convert valid digits to integer until a non-digit is found. Step 4: Clamp values beyond 32-bit signed range to [-2³¹, 2³¹ - 1]. Used a long to handle overflow safely before final conversion. ✅ ⏳ Time Complexity: O(n) 💾 Space Complexity: O(1) 📌 Example: Input: "42" → Output: 42 Input: " -042" → Output: -42 🎯 Takeaway: Always handle edge cases — whitespace, signs, and overflow — while converting strings to numbers. 💡 #LeetCode #String #Parsing #Java #ProblemSolving #100DaysOfLeetCodeChallenge 🚀

  • text

To view or add a comment, sign in

Explore content categories