Computer Science/Coding Test
LeetCode: 8. String to Integer (atoi)
focalpoint
2021. 8. 16. 16:25
class Solution:
def myAtoi(self, s: str) -> int:
def delete_whitspace(s):
idx = 0
while idx < len(s) and s[idx] == ' ':
idx += 1
return s[idx:]
def range_check(num):
upper_limit = 2**31 - 1
lower_limit = - 2**31
if num < lower_limit:
return lower_limit
if num > upper_limit:
return upper_limit
return num
if len(s) == 0:
return 0
s = delete_whitspace(s)
if not s:
return 0
first_char = s[0]
if first_char != '-' and first_char != '+' and not first_char.isdigit():
return 0
is_negative = True if first_char == '-' else False
if not first_char.isdigit():
s = s[1:]
if not s:
return 0
idx = 0
while idx < len(s) and s[idx].isdigit():
idx += 1
s = s[:idx]
if not s:
return 0
num = int(s)
if is_negative:
num *= -1
num = range_check(num)
return num