1 /*improvement on dealing with overflow accroding to this:2 * https://discuss.leetcode.com/topic/57452/c-solution-beats-1003 * 4 * Being careful about the Int_max and int_min5 * This atoi isn't thinking about special char like dot and so on.6 */7 8 classSolution {9 Public:Ten intMyatoi (stringstr) { One inti,nega_sign=1; A Long Long intRe=0;//long long re to avoid overflow - for(i=0; I<str.size (); i++)//Skip to all the blank in the front of the string - { the if(str[i]!=' ') Break; - } - if(str[i]=='+') i++;//deal with Signature - Else if(str[i]=='-') {nega_sign=-1; i++;} + while(I<str.size () &&isdigit (Str[i])) - /*When the string was over or the current char was not a valid integral number,no more conversion'll be PERFORMED. + */ A { atre=re*Ten+str[i]-'0'; - if(nega_sign==-1&&-1*re<=int_min)returnInt_min;//Overflow - Else if(nega_sign==1&&re>=int_max)returnInt_max; -i++; - } - returnre*nega_sign; in } -};
Leetcode008. String to Integer (atoi)