LeetCode--String to Integer (atoi)

来源:互联网 发布:mac滴管粉底液怎么样 编辑:程序博客网 时间:2024/05/17 07:01

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.


class Solution {public:    int atoi(const char *str)     {        string temp="";        int loc=0;        while(str[loc] != '\0')        {            if(str[loc]!=' ')                break;            loc++;        }        long long res=0;        if(str[loc] == '-')        {            while(str[loc] != '\0')            {                if(str[loc] != '0')                    break;                loc++;            }            if(str[loc] == '\0')                return 0;            for(int i=loc+1; str[i] != '\0'; i++)            {                if(str[i]<48 || str[i] > 57)                    break;                res = res*10+str[i]-48;                if(res-1 > INT_MAX)                    return INT_MIN;            }            if(res-1 > INT_MAX)                return INT_MIN;            return -res;        }        else        {            while(str[loc] != '\0')            {                if(str[loc] != '0')                    break;                loc++;            }            if(str[loc] == '\0')                return 0;            if(str[loc] == '+')                loc = loc+1;            for(int i=loc; str[i]!='\0'; i++)            {                if(str[i]<48 || str[i] > 57)                    break;                res = res*10+str[i]-48;                if(res > INT_MAX)                    return INT_MAX;            }            if(res > INT_MAX)                return INT_MAX;            return res;        }    }};


0 0
原创粉丝点击