class Solution {
public int myAtoi(String s) {
char[] chars = s.toCharArray();
int len = chars.length;
//1.去空格
int index = 0;
while (index < len && chars[index] == ' ')
index++;
//2.排除极端情况 " "
if (index == len) return 0;
//3.设置符号
int sign = 1;
char firstChar = chars[index];
if (firstChar == '-') {
index++;
sign = -1;
} else if (firstChar == '+') {
index++;
}
int res = 0, last = 0; //last 记录上一次的res,以此来判断是否溢出
while (index < len) {
char c = chars[index];
if (c < '0' || c > '9') break;
int tem = c - '0';
last = res;
res = res * 10 + tem;
if (last != res / 10) ////如果不相等就是溢出了
return (sign == (-1)) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
index++;
}
return res * sign;
}
}
LC8. 字符串转换整数 (atoi)
最新推荐文章于 2025-11-14 09:16:36 发布
本文详细介绍了如何实现将字符串转换为整数的算法,包括去除前导空格、处理正负号、避免溢出等关键步骤。通过示例代码展示了Java中的myAtoi方法,该方法能正确处理各种边界情况并防止整数溢出。
703

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



