LeetCode OJ-- String to Integer (atoi) **

时间:2024-01-11 15:09:44

https://oj.leetcode.com/problems/string-to-integer-atoi/

细节题,把一个字符串转换成整数

class Solution {
public:
int atoi(const char *str) {
if(str == NULL)
return ; // remove all spaces
int i = ;
while(str[i] != '/0' && str[i] == ' ')
{
i++;
}
// only contain spaces
if(str[i] == '/0')
return ; // 判断符号
bool isNegative = false;
if(str[i] == '-')
{
i++;
isNegative = true;
}
else if(str[i] == '+')
i++;
else
{
// not num
if(str[i] < '' || str[i] > '')
return ;
}
double ans = ;
while(str[i] != '/0' && str[i]>='' && str[i] <='')
{
ans = ans*;
ans += str[i] - '';
// 如果是正数
if(isNegative == false && ans >= INT_MAX)
{
ans = INT_MAX;
break;
}
else if(isNegative && ans >= )
{
ans = INT_MIN*(-);
break;
}
i++;
} if(isNegative)
ans = ans *(-); return ans;
}
};