首页 > 代码库 > Leetcode008. String to Integer (atoi)

Leetcode008. String to Integer (atoi)

 1 /* improvement on dealing  with overflow accroding to this: 2  * https://discuss.leetcode.com/topic/57452/c-solution-beats-100 3  *  4  * be careful about the INT_MAX and INT_MIN  5  * this atoi is not thinking about special char like dot and so on. 6  */ 7  8 class Solution { 9 public:10     int myAtoi(string str) {11        int i,nega_sign=1;12        long long int re=0;  //long long re to avoid overflow 13        for(i=0;i<str.size();i++)       //skip to all the blank in the front of the string14        {15            if(str[i]!= )break;16        }17        if(str[i]==+)i++;             // deal with signature18        else if(str[i]==-){ nega_sign=-1;i++;}19        while(i<str.size()&&isdigit(str[i]))  20 /*when the string is over or the current char is not a valid integral number,no more conversion will be performed.21 */22        {23                re=re*10+str[i]-0;24                if(nega_sign==-1&& -1*re<=INT_MIN)return INT_MIN;      //overflow25                else if (nega_sign==1&&re>=INT_MAX)return INT_MAX;26                i++;27        }28        return re*nega_sign;29     }30 };

 

Leetcode008. String to Integer (atoi)