Algorithm Day104 - String to Integer
🧩 Problem Description
LeetCode 8 - String to Integer (atoi)
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function).
The algorithm follows these steps:
- Read and ignore leading whitespaces.
- Check if the next character is
+or-(determine the sign). - Read digits until a non-digit character or end of string.
- Clamp the result within the 32-bit integer range.
Example:
1 | Input: s = "42" |
💡 First Thought (Use Built-in Functions)
One might think of using Integer.parseInt() or similar methods,
but those cannot handle invalid formats and overflow gracefully.
We need to implement the parsing logic manually.
⚙️ Optimized Approach — Manual Parsing
We manually iterate through the string, handle spaces, sign, digits, and overflow.
Java Code
1 | public class Solution { |
⏱️ Complexity Analysis
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Parse string | O(n) | O(1) |
🧠 Key Takeaways
- Manual parsing ensures robust handling of edge cases (overflow, invalid input).
- Remember to check integer boundaries before multiplication.
- Similar to C’s
atoi()but safer for modern applications.
📘 Next Step: We’ll continue exploring string-to-number conversion problems next.