[Leetcode-easy] String to Integer (atoi), leetcode-easyatoi
Requirement: String> integer
* 1. First, discard the space before the string.
* 2. Then there may be positive and negative signs (note that only one is taken. If there are multiple positive and negative signs, this string cannot be converted and 0 is returned. For example, there is a "+-2" in the test case ").
* 3. The string can contain 0 ~ If a non-numeric character is encountered, only the part before the character is taken. For example, "-00123a66" is returned as "-123 ".
* 4. If the value exceeds the int range, the boundary value (2147483647 or-2147483648) is returned ).
Train of Thought: sequential reading and sequential processing. Positive number, result = result * 10 + digit; negative number: result = reuslt * 10-digit
1 public int myAtoi (String str) {2 if (str = null | str. length () = 0) return 0; 3 str = str. trim (); 4 5 boolean negative = false; 6 int I = 0; 7 if (str. charAt (I) = '+') {8 I ++; 9} else if (str. charAt (I) = '-') {10 negative = true; 11 I ++; 12} 13 double result = 0; // you must use double first, otherwise, it will first cross-border 14 for (; I <str. length (); I ++) {15 int digit = str. charAt (I)-'0'; 16 if (digit <0 | digit> 9) break; 17 if (negative = false) {18 result = result * 10 + digit; 19 if (result> Integer. MAX_VALUE) {20 return Integer. MAX_VALUE; 21} 22} else {23 result = result * 10-digit; 24 if (result <Integer. MIN_VALUE) {25 return Integer. MIN_VALUE; 26} 27} 28} 29 return (int) result; 30}