Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. class Solution(object):
  2.     def myAtoi(self, str):
  3.         """
  4.        :type str: str
  5.        :rtype: int
  6.        """
  7.         str = str.strip()
  8.         if not str:
  9.             return 0
  10.        
  11.         max_int = (2**31)-1
  12.         min_int = -2**31
  13.        
  14.         ops = ['+', '-']
  15.         seen_number = False
  16.         seen_op = False
  17.         sign = 1
  18.        
  19.         base = 0
  20.        
  21.         for i in xrange(len(str)):
  22.             e = str[i]
  23.  
  24.             if not e.isdigit() and e not in ops:
  25.                 if not seen_number:
  26.                     return 0
  27.                 else:
  28.                     # *important* use break instead of continue/return 0
  29.                     # to not include numbers after this char but keep those before
  30.                     break
  31.                        
  32.             if e in ops:
  33.                 if seen_number or seen_op:
  34.                     # *important* use break instead of continue/return 0
  35.                     # to not include numbers after this char but keep those before
  36.                     break
  37.                 else:
  38.                     seen_op = True
  39.                     sign = 1 if e == '+' else -1
  40.            
  41.             if e.isdigit():
  42.                 # build up the number from the right side instead of left
  43.                 seen_number = True
  44.                 base *= 10
  45.                 base += int(e)
  46.                
  47.                 if sign == 1 and base > max_int:
  48.                     return max_int
  49.                 elif sign == -1 and -base < min_int:
  50.                     return min_int
  51.                
  52.         return sign*base
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement