题目描述:将string型数据转换成int型数据
int myatoi(string str) {
int sign = 1, base = 0, i = 0;
while (str[i] == ' ') { i++; }
if (str[i] == '-' || str[i] == '+') {
sign = 1 - 2 * (str[i++] == '-');
}
while (str[i] >= '0' && str[i] <= '9') {
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
if (sign == 1) return INT_MAX;
else return INT_MIN;
}
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}
我的两个坑点:
- 溢出判断,在base一步步变大的过程中判断是否溢出,不要在全部转换成int之后再判断
- 不需要遍历整个string,只需要遍历数字即可
最后
以上就是善良朋友最近收集整理的关于LeetCode_String to Integer (atoi)的全部内容,更多相关LeetCode_String内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复