class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (str == NULL)
{
return 0;
}
long long ret = 0;
const long long maxInt = 2147483647;
const long long minInt = -2147483648;
int flag = 1;
int i = 0;
while (str[i] == ' ' || str[i] == '\t')
{
++i;
}
if (str[i] == '-' || str[i] == '+')
{
flag = str[i] == '-' ? -1 : 1;
++i;
}
while (str[i] != '\0')
{
if (str[i] >= '0' && str[i] <= '9')
{
ret = ret * 10 + str[i] - '0';
if (ret * flag < minInt)
{
ret = minInt;
break;
}
else if (ret * flag > maxInt)
{
ret = maxInt;
break;
}
}
else
{
break;
}
++i;
}
return (int)(ret * flag);
}
};
LeetCode-String to Integer (atoi)
最新推荐文章于 2024-11-07 23:24:07 发布