leetcode String to Integer (atoi)Dec 27 '117626 / 35090

来源:互联网 发布:resttemplate json 编辑:程序博客网 时间:2024/06/05 18:40

String to Integer (atoi)Dec 27 '117626 / 35090

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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        unsigned int value=0;
        int temp=0;
        int flag=1;
        const char *ch=str;
        if(str == NULL)
        return 0;
        while(*ch != '\0')
        {
            if(*ch == ' ' || *ch=='\t')
            ch++;
            else
            break;
        }
        
        if(*ch=='-')
        {
            flag=-1;
            ch++;
        }
        else if (*ch=='+')
        {
            flag=1;
            ch++;
        }
        else
        {
            
        }
        
        while(*ch != '\0')
        {
            
            if(*ch<='9' && *ch>='0')
            {
                temp=value;
                value*=10;
                value+=*ch-'0';                
                if((flag==1) && (value>std::numeric_limits<int>::max()))
                {
                   return std::numeric_limits<int>::max();                         
                }
                else if((flag==-1) && (value > abs(std::numeric_limits<int>::min())))
                {
                    return std::numeric_limits<int>::min();                
                }                 
            }
            else
            {
                break;
            }
            ch++;
        }
        return value*flag;
        
    }
};