避免几个坑:
1.空字符串
2.正数负数
3.不合法的字符
4.头部为0
5.超过最大值最小值
6.头部有空格
class Solution {
public:
int myAtoi(string str) {
if(str.size()<=0) return 0;
char bottom = '0';
char top = '9';
int size = str.size();
long long int temp= 0;
int cursor = 0;
bool flag = true;
while(cursor < size && str[cursor]==' ') cursor++;//去除空格
if(str[cursor] == '-'){
flag = false;
cursor++;
}else if(str[cursor] == '+'){
cursor++;
}
while(cursor < size && str[cursor]<=top && str[cursor] >=bottom){
temp = temp * 10 + str[cursor] - bottom;
if(flag && temp > INT_MAX) return INT_MAX;
if(!flag && (temp * -1) < INT_MIN) return INT_MIN;
cursor++;
}
return flag ? temp : temp * -1;
}
};
本文介绍了一个C++实现的字符串转整型(int)函数myAtoi的具体实现过程,详细解析了如何处理空字符串、正负号、非法字符等问题,并确保转换结果不会超出整型的最大或最小值。

267

被折叠的 条评论
为什么被折叠?



