【LeetCode】【Python】8. String to Integer (atoi)

题目


Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.


实现


  1. class Solution:  
  2.     # @param {string} str  
  3.     # @return {integer}  
  4.     def myAtoi(self, str):  
  5.         INT_MAX=2147483647;INT_MIN=-2147483648  
  6.         index=0  
  7.         while index<len(str) and str[index]==' ':index+=1  
  8.         flag=1  
  9.         if index<len(str) and str[index]=='-':  
  10.             index+=1  
  11.             flag=-1  
  12.         elif index<len(str) and str[index]=='+':  
  13.             index+=1  
  14.         res=0  
  15.         while index<len(str):  
  16.             if str[index]<'0' or str[index]>'9':return flag*res  
  17.             digit=ord(str[index])-ord('0')  
  18.             if flag==1 and res*10+digit>INT_MAX:return INT_MAX  
  19.             if flag==-1 and res*10+digit>-INT_MIN:return INT_MIN  
  20.             res=res*10+digit  
  21.             index+=1  
  22.         return flag*res  

猜你喜欢

转载自blog.csdn.net/qq_16340693/article/details/70745492