LeetCode算法入门- String to Integer (atoi)-day7
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;} }總結
以上是生活随笔為你收集整理的LeetCode算法入门- String to Integer (atoi)-day7的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot 实用开发技巧——
- 下一篇: 微型计算机硬件性能取决于什么,微型计算机