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. 先判斷字符串是否爲空或者長度爲0
     if(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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章