LeetCode算法入门- String to Integer (atoi)-day7
String to Integer (atoi):
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.
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.
解法:
主要注意几个方面的内容:
这题主要就是考虑一下corner case。
越界问题?
正负号问题?
空格问题?
精度问题?
代码如下:
class Solution {public int myAtoi(String str) {//1. 先判断字符串是否为空或者长度为0if(str == null || str.length() < 1)return 0;//2. 调用String.trim()方法来去除空格str = str.trim();int i = 0;char flag = '+';//3. 判断字符串的正负,用于后面的判断if(i < str.length() && str.charAt(i) == '-'){flag = '-';i++;}else if(i < str.length() && str.charAt(i) == '+'){flag = '+';i++;}//4. 截取字符串中数字的部分,如何判断:str.charAt(i) >= '0' && str.charAt(i) <= '9'//记得result要用double类型来存储,不然可能会溢出double result = 0;while(i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){//每个字符每个字符取出来累加result = result * 10 + (str.charAt(i) - '0');i++;}//5. 利用前面的正负来给数组赋值if(flag == '-')result = -result;//6. 判断有没有超出最大值或者小于最小值if(result > Integer.MAX_VALUE)return Integer.MAX_VALUE;else if(result < Integer.MIN_VALUE)return Integer.MIN_VALUE;//最后记得将结果强制类型转换为int类型return (int)result;}
}