Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:


       Only the space character ' ' is considered as whitespace character.
       Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.


Example 1:


Input: "42"
Output: 42


Example 2:


Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.


Example 3:


Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.


Example 4:


Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:


Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

Difficulty: interview

Starter code:

class Solution:
    def myAtoi(self, s: str) -> int:
        

Solutions:
class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
         base = "0123456789"
         plus = "+"
         minus = "-"
         sum = 0
         flag = 1
         bit = 0
         INT_MAX = 2147483647
         INT_MIN = -2147483648
         
         if not str:
             return 0
         
         if len(str) == 0:
             return 0
         
         for letter in str.strip():
             if letter in plus:
                 if bit == 0:
                     bit = 1
                     continue
                 else:
                     break
             elif letter in minus:
                 if bit == 0:
                     bit = 1
                     flag = -1
                     continue
                 else:
                     break
             elif letter not in base:
                 break;
             else:
                 sum *= 10
                 sum += int(letter)
         
         sum *= flag
         
         if(sum > INT_MAX):
             return INT_MAX
         
         if(sum < INT_MIN):
             return INT_MIN
         
         return sum
                 
         


class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
         import sys
         str = str.lstrip()
         if not str:
             return 0
         negative = (str[0] == '-')
         str = str.lstrip('')
         if str[0] in ('-', '+'):
             str = str[1:]
         str.lstrip('0')
         result = 0
         for s in str:
             if s.isnumeric():
                 result *= 10
                 result += int(s)
             else:
                 break
         return max(min(result * (-1 if negative else 1), 2147483647), -2147483648)


class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
 
         str = str.strip()
         if str == '':
             return 0
         str = str.split()[0]
 
         flag = True
         if str[0] == '+':
             flag = True
             str = str[1:]
         elif str[0] =='-':
             flag = False
             str = str[1:]
 
         if str == '' or str[0] not in "0123456789":
             return 0
         s = ''
         for ch in str:
             if ch in "0123456789":
                 s += ch
             else:
                 break
         try:
             result = int(s)
         except:
             return 0
         else:
             if not flag:
                 result = -result
         if result > 2147483647:
             result = 2147483647
         elif result < -2147483648:
             result = -2147483648
         return result

class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
         INT_MAX = 2147483647
         INT_MIN = -2147483648
         str = str.strip()
         if not str:
             return 0
         sign = 1
         if str[0] in ("+", "-"):
             if str[0] == "-":
                 sign = -1
             str = str[1:]
         if not str:
             return 0
         if not str[0].isdigit():
             return 0
         for ind, val in enumerate(str):
             if not val.isdigit():
                 str = str[:ind]
                 break
         #sum = 0
         #scale = 1
         #for element in str[::-1]:
         #    sum += scale * int (element)
         #    scale *= 10
         sum = int(str)
 
             
             
         result = sign * sum
         if result > INT_MAX:
             return INT_MAX
         if result < INT_MIN:
             return INT_MIN
         return result


class Solution:
     def myAtoi(self, s):
         """
         :type str: str
         :rtype: int
         """
         count=0
         sign=1
         st='0'
         s=s.strip()
         for i in range(len(s)):
                 
             if ord(s[i])>=48 and ord(s[i])<=57:
                 st=st+s[i]
             
             elif s[i]=='+' and count==0:
                 count=1
             elif s[i]=='+' and count==1:
                 break
                 
             elif s[i]=='-' and count==0:
                 sign=-1
                 count=1
             elif s[i]=='-' and count==1:
                 break    
     
             else:
                 break
                 
         n=sign*(int(st))        
         
         if n>=2147483647:
             return 2147483647
         elif n<=-2147483648:
             return -2147483648
         else:
             return n
             


class Solution:
     def myAtoi(self, s):
         """
         :type str: str
         :rtype: int
         """
         count=0
         sign=1
         st='0'
         s=s.strip()
         for i in range(len(s)):
                 
             if ord(s[i])>=48 and ord(s[i])<=57:
                 st=st+s[i]
             
             elif s[i]=='+' and count==0:
                 count=1
             elif s[i]=='+' and count==1:
                 break
                 
             elif s[i]=='-' and count==0:
                 sign=-1
                 count=1
             elif s[i]=='-' and count==1:
                 break    
     
             else:
                 break
                 
         n=sign*(int(st))        
         
         if n>=2147483647:
             return 2147483647
         elif n<=-2147483648:
             return -2147483648
         else:
             return n
             


class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
         if len(str) == 0 : return 0
         ls = list(str.strip())
         
         sign = -1 if ls[0] == '-' else 1
         if ls[0] in ['-','+'] : del ls[0]
         ret, i = 0, 0
         while i < len(ls) and ls[i].isdigit() :
             ret = ret*10 + ord(ls[i]) - ord('0')
             i += 1
         return max(-2**31, min(sign * ret,2**31-1))

class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
         str = str.lstrip()
         if not str:
             return 0
         
         sign = -1 if str[0] == '-' else 1
         if str[0] in ['+', '-']:
             str = str[1:]
         
         i, res = 0, 0
         while i < len(str) and str[i].isdigit():
             res = res * 10 + ord(str[i]) - ord('0')
             i += 1
         
         return max(-2**31, min(2**31-1, sign * res))


class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
         # get rid of leading whitespaces
         s = str.lstrip()
         
         if len(s) == 0:
             return 0
         # get integer as far as possible        
         if s[0] not in ['+','-']:
             sign = 1
             i = 0 
             while i < len(s) and s[i].isdigit():
                 i += 1
             int_as_str = s[:i]
         else:
             sign = 1 if s[0] == '+' else -1
             i = 1
             while i < len(s) and s[i].isdigit():
                 i += 1
             int_as_str = s[1:i]
         
         # convert to integer
         if len(int_as_str) == 0:
             return 0
         
         return max(-2**31, min(sign * int(int_as_str),2**31-1))
             
         


class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
         str = str.strip()
         if len(str)==0: return 0
         
         if str[0] =="-":
             ret, i = 0, 1
             sign = -1
         elif str[0] == "+":
             ret, i = 0, 1
             sign = 1
         else:
             ret, i = 0, 0
             sign =1
         while i < len(str) and str[i].isdigit() :
             ret = ret*10 + int(str[i])
             i += 1
         return max(-2**31, min(sign * ret,2**31-1))

class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
         if not str:
             return 0
         str = str.strip()
         number, flag = 0, 1
         if str[0] == '-':
             str = str[1:]
             flag = -1
         elif str[0] == '+':
             str = str[1:]
         for c in str:
             if c >= '0' and c <= '9':
                 number = 10*number + ord(c) - ord('0')
             else:
                 break
         number = flag * number
         number = number if number <= 2147483647 else 2147483647
         number = number if number >= -2147483648 else -2147483648
         return number