LyWang

atoi

Nov 25th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. class Solution:
  2.     def atoi(self, str):
  3.         """
  4.        :type str: str
  5.        :rtype: int
  6.        """
  7.         i = 0
  8.         result = 0
  9.         length_of_number=0
  10.         numberarray=[]
  11.         intMAX=2**31 -1
  12.         intnegMAX=2**31
  13.         negative = False
  14.         while i <= len(str):
  15.             if i == len(str):
  16.                 return 0
  17.             if str[i] == '+' or str[i] == '-':
  18.                 if str[i] == '-':
  19.                     negative = True
  20.                 i += 1
  21.                 break
  22.             else:
  23.                 if str[i] == ' ':
  24.                     i += 1
  25.                 else:
  26.                     break
  27.         while i <= len(str):
  28.             if i == len(str):
  29.                 return 0
  30.             if str[i] == '0':
  31.                 i += 1
  32.             else:
  33.                 break
  34.         while i <= len(str):
  35.             if i == len(str):
  36.                 break
  37.             if str[i] in ['0','1', '2', '3', '4', '5', '6', '7', '8', '9']:
  38.                 length_of_number += 1
  39.                 numberarray.append(int(str[i]))
  40.                 i += 1
  41.             else:
  42.                 break
  43.         for nu in numberarray:
  44.             result += nu*10**(length_of_number-1)
  45.             length_of_number-=1
  46.         if negative:
  47.             if result <= intnegMAX:
  48.                 result*=-1
  49.             else:
  50.                 result = intnegMAX
  51.                 result*=-1
  52.         else:
  53.             if result > intMAX:
  54.                 result = intMAX
  55.         return result
Add Comment
Please, Sign In to add comment