一、题目概述
二、思路方向
三、代码实现
public class Solution {
public int myAtoi(String s) {
s = s.trim();
if (s.isEmpty()) return 0;
int index = 0;
int sign = 1;
long num = 0; // 使用 long 来避免在转换过程中溢出
// 检查符号
if (s.charAt(index) == '-') {
sign = -1;
index++;
} else if (s.charAt(index) == '+') {
index++;
}
// 转换数字
while (index < s.length() && Character.isDigit(s.charAt(index))) {
int digit = s.charAt(index) - '0';
// 检查溢出
if (num > Integer.MAX_VALUE / 10 || (num == Integer.MAX_VALUE / 10 && digit > 7)) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
num = num * 10 + digit;
index++;
}
return (int) (sign * num);
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.myAtoi(" -42")); // 输出 -42
System.out.println(solution.myAtoi("4193 with words")); // 输出 4193
System.out.println(solution.myAtoi("words and 987")); // 输出 0
System.out.println(solution.myAtoi("-91283472332")); // 输出 -2147483648
}
}
执行结果:
四、小结
结语