9.String to Integer (atoi)
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.
Solution:
Corner Cases: 1. Remove Whitespaces 2. Check sign 3. Check validity 4. Check min and max range
class Solution
{
public:
int myAtoi(string str)
{
int i = 0;
int res = 0;
int sign = 1;
int k = 0;
while (str[i] == 32) // Remove whitespaces
{
i++;
}
if (str[i] == '-') // Check for sign
{
sign = -1;
i++;
}
else if (str[i] == '+')
{
sign = 1;
i++;
}
while (i < str.length())
{
if (str[i] >= '0' && str[i] <= '9') // Check for validity
{
// Checking for max and min
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && str[i] - 48 > 7))
{
if (sign == 1)
{
return INT_MAX;
}
else if (sign == -1)
{
return INT_MIN;
}
}
k++;
res = res * 10 + (str[i] - 48);
}
else
{
break;
}
i++;
}
if (k == 0)
{
return 0;
}
return res * sign;
}
};
Last updated