Scribbling

LeetCode: 8. String to Integer (atoi) 본문

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

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 15. 3Sum  (0) 2021.08.19
LeetCode: 11. Container With Most Water  (1) 2021.08.17
LeetCode: 6. ZigZag Conversion  (0) 2021.08.16
LeetCode: 207. Course Schedule  (0) 2021.08.14
LeetCode: 1584. Min Cost to Connect All Points  (0) 2021.08.13