# LeetCode 8 String to Integer (atoi)

c++

class Solution {
public:
int myAtoi(string str) {

int len = str.length();
int tag=0;
int tag2=0;
char tag3='x';
string num="";
for(int i=0;i<len;i++)
{
if(str[i]!=' '&&isNumber(str[i])==0)
{
if(tag==0)
return 0;
if(tag==1)
break;
}
if(str[i]==' ')
{
if(tag==0)
continue;
if(tag==1)
break;
}

if(isNumber(str[i])==1)
{
tag=1;
if(str[i]=='+'||str[i]=='-')
{
if(num==""&&tag3!='x')
return 0;
if(tag2==1&&num!="")
break;
tag3 = str[i];
}
if(str[i]>='0'&&str[i]<='9')
{
tag2 = 1;
num+=str[i];
}
}
}
long long int z = (long long int) pow(2,31)-1;
long long int y = (z+1)*-1;
long long int ans=0;
int pos=0;
for(int i=0;i<num.length();i++)
{
if(num[i]=='0'&&pos==0)
{
continue;
}
if(num[i]!='0'&&pos==0)
{
pos=1;
ans=ans*10+(num[i]-'0');
continue;
}
if(pos==1)
{
ans=ans*10+(num[i]-'0');
}
if(ans >= z)
break;

}

if(tag3=='-')
ans=ans*-1;

if(ans > z)
{
ans = z;
}
if(ans < y)
{
ans = y;
}
return ans;

}

int isNumber(char s)
{
if(s>='0'&&s<='9')
return 1;
if(s=='+'||s=='-')
return 1;

return 0;
}
};
posted @ 2019-06-15 10:24 Shendu.CC 阅读(...) 评论(...) 编辑 收藏