Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
‘ ‘ is considered as whitespace character.Example 1:
Input: "42" Output: 42
Example 2:
Input: " -42" Output: -42 Explanation: The first non-whitespace character is ‘-‘, which is the minus sign. Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words" Output: 4193 Explanation: Conversion stops at digit ‘3‘ as the next character is not a numerical digit.
Example 4:
Input: "words and 987" Output: 0 Explanation: The first non-whitespace character is ‘w‘, which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.
1 public static int myAtoi(String str) { 2 3 // 1字符串非空判断 ""||" " 4 if (str.isEmpty() || str.trim().isEmpty()) { 5 return 0; 6 } 7 8 int index = 0; 9 int sign = 1; 10 int total = 0; 11 //1检测第一个非空字符串是什么 12 while (str.charAt(index) == ‘ ‘ && index < str.length()) { 13 index++; 14 } 15 16 //1判断这个数是正数还是负数 17 if (str.charAt(index) == ‘+‘ || str.charAt(index) == ‘-‘) { 18 sign = str.charAt(index) == ‘+‘ ? 1 : -1; 19 index++; 20 } 21 22 //1判断是否是数字,是否越界,如果越界就取越界的边界值 23 while (index < str.length()) { 24 int digit = str.charAt(index) - ‘0‘; 25 if (digit < 0 || digit > 9) { 26 break; 27 } 28 29 if (Integer.MAX_VALUE / 10 > total 30 || (Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 >= digit)) { 31 total = total * 10 + digit; 32 index++; 33 } else { 34 return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; 35 } 36 } 37 return total * sign; 38 39 }

原文:https://www.cnblogs.com/xiaoshahai/p/11454298.html