Converts the given string to a 32-bit signed integer. The conversion discards any leading whitespace characters until the first non-whitespace character is found. Then, it takes an optional initial plus or minus sign followed by as many numerical digits as possible and interprets them as a numerical
(String s)
| 23 | * @return the converted integer, or 0 if the string cannot be converted to a valid integer |
| 24 | */ |
| 25 | public static int myAtoi(String s) { |
| 26 | if (s == null || s.isEmpty()) { |
| 27 | return 0; |
| 28 | } |
| 29 | |
| 30 | s = s.trim(); |
| 31 | int length = s.length(); |
| 32 | if (length == 0) { |
| 33 | return 0; |
| 34 | } |
| 35 | |
| 36 | int index = 0; |
| 37 | boolean negative = false; |
| 38 | |
| 39 | // Check for the sign |
| 40 | if (s.charAt(index) == '-' || s.charAt(index) == '+') { |
| 41 | negative = s.charAt(index) == '-'; |
| 42 | index++; |
| 43 | } |
| 44 | |
| 45 | int number = 0; |
| 46 | while (index < length) { |
| 47 | char ch = s.charAt(index); |
| 48 | |
| 49 | // Accept only ASCII digits |
| 50 | if (ch < '0' || ch > '9') { |
| 51 | break; |
| 52 | } |
| 53 | |
| 54 | int digit = ch - '0'; |
| 55 | |
| 56 | // Check for overflow |
| 57 | if (number > (Integer.MAX_VALUE - digit) / 10) { |
| 58 | return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE; |
| 59 | } |
| 60 | |
| 61 | number = number * 10 + digit; |
| 62 | index++; |
| 63 | } |
| 64 | |
| 65 | return negative ? -number : number; |
| 66 | } |
| 67 | } |