Skip to content

Latest commit

 

History

History
54 lines (38 loc) · 1.19 KB

_8. String to Integer (atoi).md

File metadata and controls

54 lines (38 loc) · 1.19 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 10, 2024

Last updated : July 01, 2024


Related Topics : String

Acceptance Rate : 17.586 %


Solutions

Python

class Solution:
    def myAtoi(self, s: str) -> int:
        if len(s.replace(' ', '')) == 0 :
            return 0
        positive = True
        leftIndx = 0

        while s[leftIndx] == ' ' :
            leftIndx += 1

        if s[leftIndx] == '-' :
            positive = False
            leftIndx += 1
        elif s[leftIndx] == '+' :
            leftIndx += 1

        rightIndx = leftIndx
        while rightIndx < len(s) and s[rightIndx].isnumeric() :
            rightIndx += 1
        
        if (leftIndx == rightIndx) :
            return 0
        
        output = int(s[leftIndx:rightIndx]) * (1 if positive else -1)
        return min(max(output, -1 * (2**31)), 2**31 - 1)