要考虑的特殊情况有:
1、字符串开头空格(删除即可)
StringName = StringName.trim();
2、符号:用boolean判断第一个字符是+、-。没有默认为+(后续就只需要判断添加字符是否是数字字符,用boolean也解决了字符串中多个+-号问题)
3、数字长度是否超限:遍历字符时直接添加进long中并且判断大小是否超限,超限则直接返回大或小极限
代码实现:
import java.util.Scanner;
public class Demo {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String num = sc.nextLine();
int result = Solution.myAtoi(num);
System.out.println(result);
}
}
class Solution {
public static int myAtoi(String s) {
s = s.trim();
if (s.length() == 0) {
return 0;
}
boolean negative = false;
int i = 0;
if (s.charAt(0) == '-') {
negative = true;
i++;
} else if (s.charAt(0) == '+') {
i++;
}
long result = 0;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
result = result * 10 + (s.charAt(i) - '0');
if (!negative && result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (negative && -result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
i++;
}
if (negative) {
result = -result;
}
return (int) result;
}
}