#-*- coding: UTF-8 -*-
#需要考虑多种情况
#以下几种是可以返回的数值
#1、以0开头的字符串,如01201215
#2、以正负号开头的字符串,如‘+121215’;‘-1215489’
#3、1和2和空格混合形式【顺序只能是正负号-0,空格位置可以随意】的:‘+00121515’
#4、正数小于2147483647,负数大于-2147483648的数字
#其他的情况都是返回0,因此在判断 是把上述可能出现的情况列出来,其他的返回0
#AC源码如下
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if str=="":return 0
strl=[]
count=0
flag=0
str=str.strip()
for c in str:
if c>='1' and c<='9':
count+=1
strl.append(c)
elif c=='0' and count!=0:
count+=1
strl.append(c)
elif c=='-' and flag==0:
flag+=1
strl.append(c)
elif c=='+' and flag==0:
flag+=1
strl.append(c)
elif c=='0':continue
else:break
str=''.join(strl)
if str=="":return 0
if str[0]!='-'and str[0]!='+' :return int(str) if int(str)<2147483647 else 2147483647
elif str[0]=='-' and len(str)>1 :return -int(str[1:]) if int(str[1:])<2147483648 else -2147483648
elif str[0]=='+' and len(str)>1 :return int(str[1:]) if int(str[1:])<2147483647 else 2147483647
return 0
sol=Solution()
print sol.myAtoi("-2147483648")
相关文章
- 03-20【leetcode❤python】 8. String to Integer (atoi)
- 03-20【leetcode❤python】387. First Unique Character in a String
- 03-20Leetcode 8. 字符串转换整数 (atoi)(DAY 165)---- LeetCode 精选 TOP 面试题
- 03-20leetcode Reverse Integer python
- 03-20【LeetCode】387. First Unique Character in a String 解题报告(Python)
- 03-20【LeetCode】1047. Remove All Adjacent Duplicates In String 解题报告(Python)
- 03-20【leetcode❤python】 438. Find All Anagrams in a String
- 03-20【LeetCode】438. Find All Anagrams in a String 解题报告(Python)
- 03-20[LeetCode&Python] Problem 606. Construct String from Binary Tree
- 03-20[LeetCode&Python] Problem 796. Rotate String