码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--String to Integer (atoi)

时间:2015-01-08 09:41:06      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   字符串   string   

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;
        }
    }
};


LeetCode--String to Integer (atoi)

标签:leetcode   算法   字符串   string   

原文地址:http://blog.csdn.net/shaya118/article/details/42507983

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!