Implementing String to Integer Conversion (atoi) – A Step-by-Step Guide leetcode-8
String to Integer (atoi) – A Step-by-Step Guide
Introduction
Converting a string to an integer is a common problem in programming. In this blog, we will walk through a simple approach to implementing the atoi
function.
Approach
- Trim leading whitespace from the string.
- Check if the first character is a sign (`+` or `-`) and store it.
- Extract numeric characters and form the number.
- Convert the numeric string to an integer and apply the sign.
- Clamp the result within the 32-bit integer range (`[-2147483648, 2147483647]`).
Code Implementation
class Solution:
def myAtoi(self, s: str) -> int:
s = s.strip()
sign = 1
result = "0"
for i, c in enumerate(s):
if i == 0:
if c == '-':
sign = -1
elif c == '+':
sign = 1
elif c.isdigit():
result += c
else :
return 0
else :
if not c.isdigit():
break
result += c
if int(result) * sign < -2147483648:
return -2147483648
elif int(result) * sign > 2147483647:
return 2147483647
else:
return int(result) * sign
Time and Space Complexity
Time Complexity: O(n) - We traverse the string once.
Space Complexity: O(1) - We use only a few extra variables.
LeetCode Solution
You can check out my LeetCode solution here.
Comments
Post a Comment