[LeetCode] String to Integer (atoi)

来源:互联网 发布:女孩穿衣打扮知乎 编辑:程序博客网 时间:2024/06/11 06:51

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.

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) orINT_MIN (-2147483648) is returned.

  • 实现代码
/*************************************************************    *  @Author   : 楚兴    *  @Date     : 2015/2/7 14:47    *  @Status   : Accepted    *  @Runtime  : 15 ms*************************************************************/#include <iostream>#include <vector>#include <algorithm>using namespace std;class Solution {public:    int atoi(const char *str) {        long long num = 0;        while (*str == ' ')  //去掉空格        {            str++;        }        bool flag = false;  //获取可选的正负号        if (*str == '+')        {            str++;        }        else if (*str == '-')        {            flag = true;            str++;        }        //如果第一个序列的非空格字符不是有效地数字字符,则返回0        if (*str < '0' || *str > '9')        {            return 0;        }        while(*str)        {            if (*str >= '0' && *str <= '9')            {                num = num * 10 + *str - '0';                str++;                if (num > INT_MAX)                {                    if (!flag)                    {                        return INT_MAX;  //INT_MAX = 2147483647                    }                    else                    {                        return INT_MIN;  //INT_MIN = -2147483648                    }                }            }            else            {                break;            }        }        if (flag)  //加上负号        {            num = -num;        }        return num;    }};

应该特别注意越界的情况,输入数据甚至可能越long long类型的界。

0 0
原创粉丝点击