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

leetcode第八题--String to Integer (atoi)

时间:2014-10-13 01:47:48      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   strong   

Problem:

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.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

哈哈,这题也没有参考别人的代码,我是看完了以上题目,修改了七次终于通过了。

我根据requirements for atoi写,

先写了个子函数,用来返回正确的数字字符串

在这当中首先是读过前面的空格,如果第一个非空格字符不是 + - 或者数字,那么返回空字符串。如果是+号或者-号,那么后边必须紧跟数字,否则也返回空字符。如果以上都没有返回,那么就是遇到数字了,直接读到非数字部分,然后将正负号与数字一同返回字符串。

再在atoi中判断返回的字符串

我定义的是long long 型来存,通过string转换为数字long long 型(通过包含sstream头文件,利用stringstream转的),然后判断long long 型在正负情况下和INT_MAX 或 INT_MIN 的比值,特别要注意是符号的时候,如果边界不对那么很多case通过不了,我一开始用long型发现不行,才转用long long 型的。

还有就是一开始我不知道原来一定要规定开头才算。如果数字在中间,前后其他字符就不算了。例如“abc123”虽然有123,但是因为开头的不是符合要求所以就不能返回数字,直接返回0即可。

class Solution {
public:
int atoi(const char *str)
{
    string s = substringInteger(str);
    if (s.size() == 0)
        return 0;
    int positive = 1;
    if (s[0] == +)
        s = s.substr(1,s.size() - 1);
    else if(s[0] == -)
        {
            s = s.substr(1,s.size() - 1);
            positive = 0;
        }

    std::stringstream ss;
    ss<<s;
    long long result;
    ss>>result;
    if (positive == 0)
    {
        long long maxval = 2147483648; // 这里直接用数字是因为我用 INT_MAX + 1 的时候显示的是 INT_MIN的值, -1的case会出错
        if (result < maxval)
            return -1*result;
        else 
            return INT_MIN;
    }
    else
    {
        if (result < INT_MAX)
            return result;
        else
            return INT_MAX;
    }
}

private:
//leetcode7 return the sub string include interger
string substringInteger(string s)
{
    if (s.size() == 0)
        return "";
    string substring;
    int pos = -1, len = 1;
    int index = 0;
    int positive = 1;
    while(s[index] ==   && index < s.size())
    {
        index++;
    }
    if (index == s.size())
        return "";
    
    if(s[index]!=+ && s[index]!=- && !isdigit(s[index]))
        return "";
    if(s[index] == +&&index+1<s.size())
        if(!isdigit(s[index+1]))
            return "";
    if(s[index] == -&&index+1<s.size())
        {
            if(!isdigit(s[index+1]))
                return "";
            else
                positive = 0;
        }
    
    // detect till digit if exist
    while(!isdigit(s[index])&&index<s.size())
    {
        index++;
    }
    if(index == s.size())
        return "";
    // find the length of the digit
    pos = index;
    while(isdigit(s[index])&&index<s.size())
    {
        index++;
    }
    len = index - pos;
    substring = s.substr(pos,len);
    // if negative return ‘-‘ in front
    if (positive == 0)
        substring = "-" + substring;
    return substring;
}
};

这次coding中回顾并学习了 substr,sstream 中 stringstream 将string和任意型转换 INT_MAX 和 INT_MIN 特别边界处理时注意,因为有个尾数是8,还有就是代码中用中文注释的地方也要注意。

leetcode第八题--String to Integer (atoi)

标签:style   blog   http   color   io   os   ar   for   strong   

原文地址:http://www.cnblogs.com/higerzhang/p/4021331.html

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