题目来源:https://leetcode.cn/problems/string-to-integer-atoi/
大致题意:
给一个字符串,将其转为整数
首先考虑规则:
接下来按照规则处理字符串,每个规则对应处理方法为:
具体看代码:
public int myAtoi(String s) {
// 取出首尾空格
s = s.trim();
// 标记当前整数是否为负数
boolean isNeg = false;
// 当前的边界值
int limit = -Integer.MAX_VALUE;
int ans = 0;
int len = s.length();
int idx = 0;
// 判断首位是否是符号位
if (len > 0 && !Character.isDigit(s.charAt(0))) {
// 若是负数,更新标记位和边界值
if (s.charAt(0) == '-') {
isNeg = true;
limit = Integer.MIN_VALUE;
idx = 1;
} else if (s.charAt(0) == '+') {
idx = 1;
}
}
// 辅助边界值
int mulLimit = limit / 10;
while (idx < len) {
// 若当前位字符不是数字,跳出循环
if (s.charAt(idx) < '0' || s.charAt(idx) > '9') {
break;
}
// 获取当前位数字
int digit = s.charAt(idx++) - '0';
// 根据辅助位判断是否越界
if (ans < mulLimit) {
ans = limit;
break;
}
ans *= 10;
// 根据边界值判断是否越界
if (ans < limit + digit) {
ans = limit;
break;
}
ans -= digit;
}
return isNeg ? ans : -ans;
}