首页 > 其他 > 详细

[leetcode]8字符串转换整数 (atoi)

时间:2019-03-25 21:07:30      阅读:140      评论:0      收藏:0      [点我收藏+]

题目不难,但是坑多的一比。。。

特殊情况:

  ‘-’

  ‘+’

  ‘00000123’

  ‘00000000’

同时清理完之后随时对处理过的字符串的长度进行判断,考虑是否为空

 1 class Solution:
 2     def myAtoi(self, str: str) -> int:
 3         flag=1
 4         if(str==‘‘):
 5             return 0
 6         while(str[0]== ):#清除空格
 7             str=str.replace( ,‘‘,1)
 8             if(str==‘‘):
 9                 return 0
10         if(str[0]==-):
11             flag=-1
12             str=str.replace(-,‘‘,1)
13             if(str==‘‘):#修改完就立刻判断是否为空
14                 return 0
15         elif(str[0]==+):
16             str=str.replace(+,‘‘,1)
17             if(str==‘‘):
18                 return 0
19         if(0>str[0] or str[0]>9):
20             return 0
21         i=0
22         ans=‘‘
23         while((i<len(str))and(0<=str[i]<=9)):
24             ans+=str[i]
25             i=i+1
26         while((ans!=‘‘)and(ans[0]==0)):#运算结束后清除开头1,同时考虑输入全为0
27             ans=ans.replace(0,‘‘,1)
28         if(ans==‘‘):
29             return 0
30         ans0=flag*eval(ans)
31         ans0=max(ans0,-2**31)
32         ans0=min(ans0,2**31-1)
33         return ans0
34             

 

[leetcode]8字符串转换整数 (atoi)

原文:https://www.cnblogs.com/trickofjoker/p/10596596.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!