Monday, September 10, 2018

Implement atoi which converts a string to an integer

Implement atoi which converts a string to an integer

Example 1:
Input: "42"
Output: 42
Example 2:
Input: "   -42                    "
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.
class Solution {
public:
    int myAtoi(string str) {

        str.erase(0, str.find_first_not_of(' '));
        str.erase(str.find_last_not_of(' ')+1);

        int len = str.length();
        long long res = 0;
        bool isnegative = str[0] == '-' ? true : false;
        bool ispositive = str[0] == '+' ? true : false;
        int i;
        if (isnegative || ispositive)
            i = 1;
        else
            i = 0;
        long check = isnegative ? 2147483648 : 2147483647;

        for (; i < len; i++)
        {
            if ((str[i] == ' ') || (str[i] - '0' < 0) || (str[i] - '0' > 9))
                break;
           
            if (((res * 10) < check) && (((res * 10 + str[i] - '0') < check)))
            {
                res =  (res * 10 + str[i] - '0');
            }
            else
            {
                res = (true == isnegative) ? INT_MIN : INT_MAX;
                return res;
            }
        }
       
        if (true == isnegative)
        {
            res = -res;
        }
       
        return res;
    }
};

No comments:

Post a Comment