CODE/Algorithms & Data Structures

[LeetCode] String to Integer (atoi)

BoriTea 2021. 10. 2. 10:13

 

 

Problem

 

 


 

Solution

 

 

1. Pass all the leading whitespaces

2. Flag the sign if it is present in the beginning

3. Go through the rest of the string or until nonnumeric string is seen

 

Recognize numeric string using ASCII table.

Every time the code reads a character in the given string, it needs to determine if the number will be out of the 32-bit unsigned integer bound. 

The way that we are forming the number is multiply 10 to the current number and add the digit that is read(since current digits are being shifted to the right). We can divide the maximum integer by 10 and see if current number is larger than that. Also, if the number is equal to the result and the digit that is read is equal to the number dropped by division, it means that this string is right at the boundary. Therefore, we can return the max integer or min integer according to the sign flag.

 

class Solution(object):
    def myAtoi(self, s):
        """
        :type s: str
        :rtype: int
        """
        INTMAX = 2147483647
        INTMIN = -2147483648
        length = len(s)
        positive = True
        i = 0
        num = 0
        
        if not s:
            return num
        
        while i < length and s[i].isspace():
            i += 1
            
        if i < length and s[i] == '-':
            positive = False
            i += 1
        elif i < length and s[i] == '+':
            i += 1
        
        while i < length and '0' <= s[i] and s[i] <= '9':
            if num > INTMAX // 10 or (num == INTMAX // 10 and ord(s[i]) - ord('0') > 7):
                if positive:
                    return INTMAX
                else:
                    return INTMIN
            num = num * 10 + (ord(s[i]) - ord('0'))
            i += 1
            
        if positive:
            return num
        else:
            return -1*num