今天继续刷LeetCode,第8题,将字符串转化为整数
分析:主要考虑多种情况
1、前面存在多个空格的情况;
2、正负号的识别;
3、末尾不是数字的情况;
4、整数的大小超过(-2^31 2^31-1);
问题:
1、Python中正则化的使用;
附上C++代码:
class Solution {
public:
int myAtoi(string str) {
int flag=1;
int i=0;
while(str[i]==' ')
{
i++;
}
if(str[i]=='+')
{
flag=1;
i++;
}
else if(str[i]=='-')
{
flag=-1;
i++;
}
long long s=0;
while(str[i]!='\0')
{
if('0'<=str[i]&&str[i]<='9')
{
s=s*10+(str[i]-'0');
if(s>INT_MAX)
{
if(flag==1)
return INT_MAX;
else
return INT_MIN;
}
i++;
}
else
break;
}
s=s*flag;
return s;
}
};
附上Python代码1:
class Solution:
def myAtoi(self, str: str) -> int:
s=0
j=0
flag=1
while j<len(str):
if str[j]==' ':
j+=1
else:
break
if str[j]=='+':
flag=1
j+=1
elif str[j]=='-':
flag=-1
j+=1
while j<len(str):
if str[j]>='0' and str[j]<='9':
s=s*10+int(str[j])
if s>2**31:
if flag==1:
return 2**31-1
else:
return -2**31
j+=1
else:
break
return s*flag
附上Python代码2:
class Solution:
def myAtoi(self, str: str) -> int:
import re
res=re.findall(r'^[\+\-]?\d+',str.strip())
if res!=[]:
if int(res[0])>(2**31-1):
return 2**31-1
elif int(res[0])<(-2**31):
return -2**31
else:
return int(res[0])
else:
return 0