【8】String to Integer (atoi)

来源:互联网 发布:网络推广外包收费 编辑:程序博客网 时间:2024/05/22 17:05

此题主要就是注意一些trick

前导空格、非数字字符、溢出等

int myAtoi(string str) {        int res=0;        int max_inf=0x7fffffff;        int min_inf=0x80000000;        int p=1;          int i=0;        while(isspace(str[i])||str[i]=='0')i++;        if(str[i]=='-'){p=-1;i++;}        else if(str[i]=='+')i++;        else if(str[i]<'0'||str[i]>'9')return 0;        for(;i<str.length();i++)        {            int newd=str[i]-'0';            if(str[i]<'0'||str[i]>'9')break;            if(p==1&&(res>max_inf/10 || res==max_inf/10&&(newd>max_inf%10)))return max_inf;            if(p==-1&&(res>max_inf/10 || res==max_inf/10&&(newd>-(min_inf%10))))return min_inf;            res=res*10+newd;        }        if(p==-1)res=-res;        return res;    }

0 0