leetcode 8:String to integer(atoi)

题目原文:

  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 opthion 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 avalid 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.

  题意:实现atoi

  数字开头可能有空格

  有符号

  中间有字母处理字母之前的数字

  比较大小的话用longlong就没问题了

  解答:

  class solution
{
public:
    int atoi(const char* str)
    {
        int num = 0;
        int sign = 1;
        const int n = strlen(str);
        int i = 0;
        while (str[i] == ' '&&i < n)
            i++;
        if (str[i] == '+')   //判断正负号
            i++;
        if (str[i] == '-')
        {
            sign = -1;
            i++;
        }
        for (; i < n; i++)
        {
            if (str[i]<'0' || str[i]>'9')
                break;
            if (num>INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10))
            {
                return sign == -1 ? INT_MIN : INT_MAX;
            }
            num = num * 10 + str[i] - '0';
        }
        return num*sign;
    }
};

 注意:在写的时候会出现C4146错误,不妨将#define INT_MIN -2147483648写成#define INT_MIN (-2147483647-1).(具体原因是跟数据存储有关,这里不再探究)

原文地址:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/6397792.html