//此题是easy题,比较简单,主要困难在考虑全输入的各种情况:
//1、开始的时候有空格等空白字符
//2、开头有加减号
//3、溢出(第一次写就是没有考虑到这个情况)
//C代码
int myAtoi(char* str) {
int i=0;
double result = 0;
int IsNegative = 0;
while(isspace(str[i]))
{
i++;
}
if(str[i] == '-')
{
IsNegative = 1;
i++;
}
else if(str[i] == '+')
{
IsNegative = 0;
i++;
}
else
{
}
for(;i<strlen(str);i++)
{
if(isdigit(str[i]))
{
result = result*10 + (str[i] - '0');
}
else
{
break;
}
}
if(IsNegative == 1)
{
result *= (-1);
}
if(result > INT_MAX)
{
result = INT_MAX;
}
if(result < INT_MIN)
{
result = INT_MIN;
}
return (int)result;
}
#python代码
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
num = "1234567890"
INT_MAX = 2147483647
INT_MIN = -2147483648
i = 0
sum = 0
flag = 1
str = str.strip()
if len(str) == 0:
return 0
else:
if str[i] == '-':
flag = -1
i+= 1
elif str[i] == '+':
flag = 1
i+= 1
if i >= len(str):
return 0
while i<len(str) and str[i].isdigit():
tempint = int(str[i])
if INT_MAX/10 >= sum:
sum = sum*10
else:
if flag == 1:
return INT_MAX
if flag == -1:
return INT_MIN
if INT_MAX - tempint >= sum:
sum += tempint
else:
if flag == 1:
return INT_MAX
if flag == -1:
return INT_MIN
i+=1
return sum*flag