본문 바로가기

PS/릿코드

[릿코드 8] String to Integer (atoi) (파이썬/python)

728x90

https://leetcode.com/problems/string-to-integer-atoi/description/

 

String to Integer (atoi) - LeetCode

Can you solve this real interview question? String to Integer (atoi) - Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: 1. Read

leetcode.com

단순히 문제에서 제시하는 상황을 구현하는문제였습니다.

 

class Solution:
    def myAtoi(self, s: str) -> int:
        PLUS = "+"
        MINUS = "-"
        MAX_INT = (2 ** 31) - 1
        MIN_INT = -2 ** 31

        answer = ""
        s = s.lstrip()

        if s and s[0] == MINUS:
            answer += MINUS
            s = s[1:]
        elif s and s[0] == PLUS:
            s = s[1:]

        for target in s:
            if target.isdigit():
                answer += target
            else:
                break
        print(answer)
        if not answer or answer == MINUS:
            return 0

        int_answer = int(answer)

        if int_answer > MAX_INT:
            int_answer = MAX_INT
        elif int_answer < MIN_INT:
            int_answer = MIN_INT

        return int_answer
728x90