LeetCode String to Integer (atoi)(008)解法總結

NewCoder1024發表於2020-03-15

描述

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:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) 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.複製程式碼

思路

對字串進行完善的清洗,並轉化為int型返回即可。

經過不斷的打磨,完成了在各種測試用例下的完備性考驗。

LeetCode String to Integer (atoi)(008)解法總結

其中有0-100000000000123456-0  123等用例。

下面的是通過的程式碼:

class Solution {
    public int myAtoi(String str) {
        //新建StringBuffer暫存清洗過的資料
        StringBuffer sb = new StringBuffer();

        //posi是符號標誌,flag記錄的是此前有沒有有效輸入“-”、數字等
        boolean posi = true, flag = true;
        int posicount = 0;
        for(int i =0;i<str.length();i++){

            //有效輸入“-”、數字等碰到空格直接退出讀取
            if(str.charAt(i) == ' '){
                if(flag){
                   continue; 
                }else{
                    break;
                }
            //有效輸入後不能碰到符號,下同
            }else if(str.charAt(i) == '-' && flag){
                posi = false;
                posicount++;
                flag = false;
            }else if(str.charAt(i) == '+' && flag){
                posi = true;
                posicount++;
                flag = false;
            //記錄數字,並改變有效數字記錄位
            }else if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                sb.append(str.charAt(i));
                flag = false;
            //非法輸入的出口
            }else{
                break;
            }
        }
        
        //有兩個以上符號或者清洗過的數字長度為0
        if(posicount > 1 || sb.length() == 0){
            return 0;
        }
        
        //防止一些超長的但是沒有整型溢位的輸入:00000000000000012233444
        double sum = 0;
        for(int i = 0;i < sb.length();i++){
            sum = sum * 10 + sb.charAt(i) - '0';
        }
        
        //根據符號位調整符號
        if(!posi){
            sum = -sum;
        }

        //判斷整型溢位
        if(sum <= (double)Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }else if(sum >= (double)Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        
        return (int)sum;
    }
}複製程式碼
Runtime: 2 ms, faster than 81.23% of Java online submissions for String to Integer (atoi).
Memory Usage: 38.7 MB, less than 5.59% of Java online submissions for String to Integer (atoi).

由此可見,好的測試用例是能夠大大的提高程式的健壯性和魯棒性的


相關文章