8. String to Integer (atoi)#
1class Solution {
2
3 public int myAtoi(String s) {
4 if (s.length() == 0) return 0;
5
6 int startIndex = 0;
7 while (
8 startIndex < s.length() && Character.isWhitespace(s.charAt(startIndex))
9 ) {
10 startIndex++;
11 }
12
13 int sign = 1;
14 if (
15 startIndex < s.length() &&
16 (s.charAt(startIndex) == '-' || s.charAt(startIndex) == '+')
17 ) {
18 sign = s.charAt(startIndex) == '-' ? -1 : 1;
19 startIndex++;
20 }
21
22 long result = 0;
23
24 for (int i = startIndex; i < s.length(); ++i) {
25 char c = s.charAt(i);
26 if (!Character.isDigit(c)) {
27 break;
28 }
29
30 result = result * 10 + (c - '0');
31
32 if (sign * result <= Integer.MIN_VALUE) {
33 return Integer.MIN_VALUE;
34 }
35 if (sign * result >= Integer.MAX_VALUE) {
36 return Integer.MAX_VALUE;
37 }
38 }
39
40 return (int) (sign * result);
41 }
42}