Leetcode # 8. String to Integer (atoi)
- 2023.07.21
- Deterministic Finite Automaton LeetCode Parsing
https://leetcode.com/problems/string-to-integer-atoi
Solution
Time Complexity: O(len(s))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)
class Solution: def myAtoi(self, s: str) -> int: i = p = 0 sign = 1 # Q0: Ignore whitespaces while p < len(s): if s[p] != " ": break p += 1 # Q1: Check if the next character is "+" or "-" if p < len(s): match s[p]: case "+" | "-": sign = 1 if s[p] == "+" else -1 p += 1 # Read in digit characters while p < len(s): o = ord(s[p]) if o < 48 or o > 57: break # If the integer < -2^31, return -2^31 # If the integer > (2^31 - 1), return (2^31 - 1) if i == 214748364: if sign > 0 and o - 48 > 7: return 2147483647 if sign < 0 and o - 48 > 8: return -2147483648 elif i > 214748364: return 2147483647 if sign > 0 else -2147483648 i = i * 10 + (o - 48) p += 1 return sign * i
Last Updated on 2023/08/16 by A1go