Python
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip()
_sum = 0
if len(str) == 0:
pass
elif str[0].isdigit():
for i in str:
if i.isdigit():
_sum = _sum * 10 + int(i)
else:
break
elif str[0] == '-' or str[0] == '+':
for i in range(1, len(str)):
if str[i].isdigit():
_sum = _sum * 10 + int(str[i])
else:
break
if (str[0] == '-'):
_sum *= -1
_max = 2 ** 31 - 1
_min = -2 ** 31
if _sum < _min:
_sum = _min
if _sum > _max:
_sum = _max
return _sum
C++
class Solution {
public:
int myAtoi(string str)
{
char s[str.length() + 1];
long long int x = 0;
for (int i = 0; i < str.length(); i++)
{
s[i] = str[i];
}
s[str.length()] = '\0';
sscanf(s, "%lld", &x);
int _min = 1 << 31, _max = ~(1 << 31);
if (x < _min)
{
x = _min;
}
else if (x > _max)
{
x = _max;
}
return (int)x;
}
};