[LeetCode][python3]0008. String to Integer (atoi)

Start the Journey
N2I -2020.03.15

1. My first solution


  1. class Solution:
  2. def myAtoi(self, str: str) -> int:
  3. str2=''
  4. if not str:
  5. return 0
  6. for index,i in enumerate(str):
  7. if i in ['1','2','3','4','5','6','7','8','9','0']:
  8. break
  9. elif i!=' ':
  10. break
  11. if i=='+':
  12. index+=1
  13. if i=='-':
  14. str2+=i
  15. index+=1
  16. for i in range(index,len(str)):
  17. if str[i] in ['1','2','3','4','5','6','7','8','9','0']:
  18. str2+=str[i]
  19. else:
  20. break
  21. if not str2 or str2=="-":
  22. return 0
  23. x=int(str2)
  24. if x > 2147483648-1:
  25. return 2147483648-1
  26. elif x<-2147483648:
  27. return -2147483648
  28. return x
  29.  

Explanation:

Though this is an easy one, it is still bothering to deal with the exceptions.


2. Other Answer


  1. class Solution:
  2. def myAtoi(self, str: str) -> int:
  3. num = ""
  4. for char in str:
  5. if num != "" and char in " +-":
  6. break
  7. if char in '1234567890-+':
  8. num += char
  9. elif char != " ":
  10. break
  11. if num in "+-":
  12. return 0
  13. else:
  14. return min(max(int(num),-2**31),2**31-1)
  15.  

Explanation:

This solution is more clean, but a little slower.