LeetCode 8: String to Integer (atoi) – Python & JavaScript Solutions Explained
String to Integer (atoi) - LeetCode Problem 8
Difficulty: Medium
Problem Statement
Implement the atoi function, which converts a string into an integer.
Approach & Explanation
- Remove leading whitespace.
- Check for a sign (+ or -).
- Extract numerical digits.
- Clamp to 32-bit integer limits.
Python Solution:
import re
def myAtoi(s: str) -> int:
match = re.match(r'^[\+\-]?\d+', s.lstrip())
if not match:
return 0
num = int(match.group())
return max(min(num, 2**31 - 1), -2**31)
JavaScript Solution:
function myAtoi(s) {
let num = parseInt(s.trim(), 10);
if (isNaN(num)) return 0;
return Math.max(Math.min(num, 2**31 - 1), -(2**31));
}
Time Complexity
O(n) because we parse each character.
Comments
Post a Comment