Leetcode008. String to Integer (atoi)

时间:2023-03-09 05:50:27
Leetcode008. String to Integer (atoi)
 /* improvement on dealing  with overflow accroding to this:
* https://discuss.leetcode.com/topic/57452/c-solution-beats-100
*
* be careful about the INT_MAX and INT_MIN
* this atoi is not thinking about special char like dot and so on.
*/ class Solution {
public:
int myAtoi(string str) {
int i,nega_sign=;
long long int re=; //long long re to avoid overflow
for(i=;i<str.size();i++) //skip to all the blank in the front of the string
{
if(str[i]!=' ')break;
}
if(str[i]=='+')i++; // deal with signature
else if(str[i]=='-'){ nega_sign=-;i++;}
while(i<str.size()&&isdigit(str[i]))
/*when the string is over or the current char is not a valid integral number,no more conversion will be performed.
*/
{
re=re*+str[i]-'';
if(nega_sign==-&& -*re<=INT_MIN)return INT_MIN; //overflow
else if (nega_sign==&&re>=INT_MAX)return INT_MAX;
i++;
}
return re*nega_sign;
}
};