Convert String to 32-bit Signed Integer (atoi)

🚀 LeetCode — Problem 8 | Day 13 💡 Problem: String to Integer (atoi) --- 🧠 Problem: Convert a string into a 32-bit signed integer (like C/C++ atoi). --- 🧠 Approach: - Skip leading whitespaces - Check sign (+ / -) - Convert digits one by one - Stop at first non-digit character - Handle overflow before it happens --- ⚙️ Core Logic: - Build number step-by-step: result = result * 10 + digit - Before adding digit, check: • If result > Integer.MAX_VALUE / 10 • Or result == MAX/10 and digit > 7 👉 Return: - Integer.MAX_VALUE (overflow) - Integer.MIN_VALUE (underflow) --- ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) --- ⚠️ Edge Cases: - " 42" → leading spaces - "-42" → negative number - "42abc" → stop at non-digit - "abc" → no digits → return 0 - Large values → handled overflow --- 🔍 Insight: Careful parsing is more important than complex logic --- 🔑 Key Learning: - Step-by-step string parsing - Handling edge cases cleanly - Preventing overflow before it occurs - Real-world input validation logic --- #LeetCode #DSA #Java #CodingJourney

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories