Leetcode(4) - String to Integer

Implement  atoi, convert string to integer.

The space character needs to be removed from the string before the first non-blank character is found. If the first non-blank character is a positive sign or a negative sign, select that sign and combine it with as many consecutive digits as possible. This part of the character is the value of the integer. If the first non-blank character is a digit, it is directly combined with subsequent consecutive digit characters to form an integer.

Strings can include extra characters after the characters that form the integer, these characters can be ignored, they have no effect on the function.

No conversion occurs when the first sequence of non-empty characters in the string is not a valid integer; or when the string is empty; or when the string contains only whitespace characters.

Returns 0 if the function cannot perform a valid conversion.

illustrate:

Suppose our environment can only store 32-bit signed integers in the range [−2^31, 2^31 − 1]. Returns INT_MAX (2^31 − 1) or INT_MIN (−2^31) if the value exceeds the representable range.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "-42"
output: -42
Explanation: The first non-whitespace character is '-', which is a minus sign.
     We try to combine the minus sign with all consecutive numbers that follow, and we end up with -42.

Example 3:

输入: "4193 with words"
Output: 4193
Explanation: Conversion ends at digit '3' because its next character is not a digit.

Example 4:

Input: "words and 987"
output: 0
Explanation: The first non-blank character is 'w', but it is not a digit or a plus or minus sign.
     Therefore a valid conversion cannot be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" exceeds the range of a 32-bit signed integer.
     So INT_MIN (−231) is returned.
class Solution {
public:
   int myAtoi(string str)
{
    if(str.empty())
    {
        return 0;
    }
    int i=0,out=0;
    int flag=1;
    while(isspace(str[i]))
    {
        i++;
    }
    if(str[i]=='-')
    {
        flag=-1;
        i++;
    }
    else if(str[i]=='+')
    {
        flag=1;
        i++;
    }
    while(i<str.size())
    {
        if(isdigit(str[i]))
        {
            if(out>INT_MAX/10)
            {
                if(flag>0)
                    return INT_MAX;
                else
                    return INT_MIN;
                break;
            }
            else if(out==INT_MAX/10 && str[i]-'0'>7)
            {
                return (flag>0)? INT_MAX : INT_MIN;
            }
            else
            {
                    out = out * 10;
                    out+=str[i]-'0';
                    i++;
            }
        }
        else 
            break ;
    }
    return out*flag;
}
};

C provides the atoi function, which can convert strings into integers, but it is not available in all compilers, so in many cases, we need to implement this function ourselves, just to find out what is inside the library function atoi how to achieve.

The idea of ​​the program written by myself is as follows: (1) First determine whether the string is empty, if it is empty, return 0; (2) When the string is not empty, continue to use the isspace function to change the space and tab characters at the beginning (3) If the first non-numeric character is a positive or negative sign, it represents the positive or negative of the number, and it is necessary to judge at the same time here, otherwise, an error will occur when processing a string such as "-+1". (4) Then judge whether it is followed by a number. If not, return 0. If it is, process it and traverse it until the first non-numeric character is encountered. (5) Judgment beyond the boundary, it is very confusing here. Pay special attention to the special numbers around INT_MAX, INT_MIN.

Excellent code is as follows:

class Solution {
public:
   int myAtoi(string str) 
{
    if (str.empty()) return 0;
    int sign = 1, base = 0, i = 0, n = str.size();
    while (i < n && str[i] == ' ') ++i;
    if (str[i] == '+' || str[i] == '-')
    {
        sign = (str[i++] == '+') ? 1 : -1;
    }
    while (i < n && str[i] >= '0' && str[i] <= '9')
    {
        if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7))
        {
            return (sign == 1) ? INT_MAX : INT_MIN;
        }
        base = 10 * base + (str[i++] - '0');
    }
    return base * sign;
}
};

The idea is the same, but this code is written more concisely

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324973808&siteId=291194637