String to Integer (atoi)

来源:互联网 发布:易建联nba数据统计 编辑:程序博客网 时间:2024/06/05 19:15
class Solution {public:    int atoi(const char *str) {        if(!str)        {            return 0;        }        int index=0;        if(str[index]==' ')        {            while(str[index]&&str[index]==' ')            {                index++;            }        }        bool negative=false;        if(str[index]=='-')        {            index++;            negative=true;        }        else if(str[index]=='+')        {            index++;        }        bool leadingZero=true;        long long res=0;        while(str[index])        {            if(str[index]>'9'||str[index]<'0')            {               break;            }            if(leadingZero&&str[index]=='0')            {                index++;            }            else            {                leadingZero=false;                res*=10;                res+=str[index]-'0';                index++;               }            if(res-1>(1<<31)-1)            {                res=(1<<31)-1;                res++;                break;            }        }        if(negative)        {            if(res-1>(1<<31)-1)            {                res=1<<31;            }            return -res;        }        else        {            if(res>(1<<31)-1)            {                res=(1<<31)-1;            }            return res;        }    }};

0 0