Skip to content

Instantly share code, notes, and snippets.

@shaziwnl
Created March 12, 2024 20:16
Show Gist options
  • Save shaziwnl/fba8bc4b1f44cafd8792cacc87704658 to your computer and use it in GitHub Desktop.
Save shaziwnl/fba8bc4b1f44cafd8792cacc87704658 to your computer and use it in GitHub Desktop.
String to integer (Leetcode 8) easy python solution
class Solution(object):
def myAtoi(self, s):
"""
:type s: str
:rtype: int
"""
sign = ""
res = 0
number_read = False
for i in range(len(s)):
if s[i] == '+' or s[i] == '-':
if sign or number_read: break
else: sign = s[i]
elif s[i] >= '0' and s[i] <= '9':
number_read = True
res *= 10
res += int(s[i])
elif s[i] == ' ':
if number_read or sign: break
else: break
int_max = (2 ** 31) - 1
int_min = -2 ** 31
if sign == '-': res *= -1
if res > int_max: return int_max
if res < int_min: return int_min
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment