1. 程式人生 > >【leetcode】8. String to Integer (atoi)(從string中按照規則提取int)

【leetcode】8. String to Integer (atoi)(從string中按照規則提取int)

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.

  • 【函式說明】atoi() 函式會掃描 str 字串,跳過前面的空白字元(例如空格,tab縮排等),直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字串結束時(’\0’)才結束轉換,並將結果返回。
  • 【返回值】返回轉換後的整型數;如果 str 不能轉換成 int 或者 str 為空字串,那麼將返回 0。如果超出Integer的範圍,將會返回Integer最大值或者最小值。
  • 【處理思路】按照函式說明來一步步處理。首先判斷輸入是否為null。然後使用trim()函式刪掉空格。判斷是否有正負號,做一個標記。返回的是整形數,可以使用double來暫存結果。按位來計算出結果。如果遇到非數字字元,則返回當前結果。加上前面的正負號。結果若超出了整形範圍,則返回最大或最小值。最後返回處理結果。
class Solution {
    public int myAtoi(String str) {
           str = str.trim();   // kill add white spaces
          if (str == null || str.length() < 1) {
            return 0;
        }
     
        int i = 0;          // index of str
        char flag = '+';    // default positive
        if (str.charAt(0) == '-') {
            flag = '-';
            i++;
        } else if (str.charAt(0) == '+') {
            i++;
        }
        double res = 0;
        // abandon the non-digit char; calculate the result
        while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            res = res * 10 + str.charAt(i) - '0';
            i++;
        }
        if (flag == '-') res = -1 * res;
        if (res > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        } else if (res < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
        return (int) res;
    }
}