您的位置:首页 > 其它

LeetCode--String to Integer (atoi)

2015-01-07 23:49 330 查看
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;
        }
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: