Created
October 7, 2022 08:13
-
-
Save ysinjab/23314cdca3cddf8cb8e225542f77c213 to your computer and use it in GitHub Desktop.
8. String to Integer (atoi)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def myAtoi(self, s): | |
""" | |
:type s: str | |
:rtype: int | |
""" | |
splitted = s.split(' ') | |
for i in splitted: | |
if not i: | |
continue | |
else: | |
r = re.findall(r"^[-+]?[0-9]+", i) | |
print(r) | |
if not r: | |
return 0 | |
else: | |
number = r[0] | |
if number[0].isdigit(): | |
number = int(number) | |
else: | |
number = -1 * int(number[1:]) if number[0] == '-' else int(number[1:]) | |
if number < -1 * (2 ** 31): | |
number = -1 * (2 ** 31) | |
elif number > (2 ** 31) - 1: | |
number = (2 ** 31) - 1 | |
return number | |
return 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment