//#8 String to Integer (atoi)
//8ms 100%
class Solution {
public:
int myAtoi(string str)
{
int result(0);
bool negative(false);
bool start(false);
for(string::iterator it = str.begin(); it!=str.end(); it ++)
{
if(*it != ' ')
{
if(*it > 47 && *it < 58)
{
if( (result >= 214748365) || ((result == 214748364) && (*it >= 56)) )
{
//cout << "result: " << result << ", *it: " << *it;
//cout << " overflow\n";
if(negative)
{
return -2147483648;
}
else
{
return 2147483647;
}
}
//cout << "result: " << result << ", *it: " << *it;
//cout << " not overflow\n";
result = result * 10 + int(*it - '0');
}
else if(*it == '-' || *it == '+')
{
if(start) return 0;
if(*it == '-') negative = true;
}
else
{
if(start)
{
break;
}
else
{
return 0;
}
}
start = true;
}
else
{
if(start)
{
break;
}
}
}
if(negative) result = result * -1;
return result;
}
};
[Leetcode]#8 String to Integer (atoi)
最新推荐文章于 2024-07-25 11:15:54 发布