首页 > 代码库 > LeetCode中String to Integer (atoi) 字符串转换成整数

LeetCode中String to Integer (atoi) 字符串转换成整数

int atoi(const char *str) {

long long result = 0;
while (*str==‘ ‘)str++;
int flag=0;
if (*str == ‘-‘ || *str == ‘+‘)
{
flag = (*str == ‘-‘) ? -1 : 1;
str++;
}
while (*str!=‘\0‘)
{
int temp = *str - ‘0‘;
if (temp >= 0 && temp <= 9)
{
result = result * 10 + temp;
if (result > 2147483647){
return (flag >= 0) ? 2147483647 : -2147483648;//这句话在VS2013中编译出错无法返回负数,leetcode上AC
}
}
else if (flag != 0 && (*str == ‘+‘ || *str == ‘-‘))return 0;
else break;
str++;
}
if (flag == 0) flag = 1;
result = flag*result;
return result;
}

LeetCode中String to Integer (atoi) 字符串转换成整数