String to Integer (atoi)

Problem Id: 8 Difficulty: Medium Tag: Math Tag: String


Intuition

Simply follow the instructions step by step.

Solution


import string


class Solution:
    def myAtoi(self, s: str) -> int:
        index = 0
        state = 0

        result = 0
        positive = 1
        while True:
            if index >= len(s):
                break

            if state == 0:
                if s[index] == ' ':
                    index += 1
                else:
                    state = 1
            elif state == 1:
                if s[index] == '-':
                    positive = -1
                    state = 2
                    index += 1
                elif s[index] == '+':
                    state = 2
                    index += 1
                else:
                    state = 2
            elif state == 2:
                if s[index] not in string.digits:
                    break
                result = result * 10 + int(s[index])
                index += 1

        result = positive * result
        if result < - 2 ** 31:
            result = - 2 ** 31
        elif result > 2 ** 31 - 1:
            result = 2 ** 31 - 1
        return result