Leetcode 8. String to Integer (atoi)

String to Integer

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 a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. If the numerical value is out of the range of representable values, 2^31 − 1 or −2^31 is returned.

Note:

  • Only the space character ' ' is considered a whitespace character.
  • Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
String to Integer (atoi)

String to Integer (atoi) :

  1. 字串前後若有空字元,不影響轉換:
    字串進來先執行 str.strip() 即可
  2. 有非數字字元的狀況:這狀況有兩種,一種非數字字元(非正負號)是出現字首,則回傳 0 ;若非數字字元出現在中間或字尾,則將非數字字元之後全部省略。
  3. 將這些數字轉換為整數(即​​“123”-> 123、“0032”-> 32)。如果未讀取任何數字,則整數為0。根據需要更改符號
  4. 如果整數超出32 位有符號整數範圍[-2 31 , 2 31 – 1],小於-2 31的整數應限制為-2 31,大於2 31 – 1 的整數應限制為2 31 – 1。

Python

class Solution:

    def myAtoi(self, str: str) -> int:

        MAX=2147483647
        MIN=-2147483648
        str=str.strip()          #清除空白

        if len(str)==0:
            return 0

        val,marks=0,1

        if str[0]=='-':          #負號,marks設-1,最後乘
            str=str[1:]
            marks=-1
        elif str[0]=='+':
            str=str[1:]     
        for i in str:
            if i>='0' and i<='9':
                val=val*10+ord(i)-ord('0')   #str轉數字
            else:
                break
        val=marks*val
        val=val if val<=MAX else MAX
        val=val if val>=MIN else MIN
        return val

C++

比如範例輸入s = ” -42″,回傳-42

s = “4193 with words”,4193後出現非數字字元,所以只需解析前面的數字,回傳4193

s = “words and 987″,一開始出現非數字字元,屬於非合理的數字,回傳0

s = “-91283472332″,低於32位元整數的下限,所以回傳32位元整數的下限-2147483648

isdigit(c)是C語言中的一個函數,可用於檢查傳遞的字符是否為數字

using namespace std;

class Solution {
public:
    int myAtoi(string s) {
        int n = s.length();
        bool Positive = true;
        int i;
        for(i = 0 ; i < n;++i){
            if(s[i] != ' ' && s[i] != '+' && s[i] != '-' && !isdigit(s[i])){
                return 0;
            }
            else if(s[i] == ' '){
                continue;
            }
            else if(s[i] == '+'){
                ++i;
                break;
            }
            else if(s[i] == '-'){
                ++i;
                Positive = false;
                break;
            }
            else{
                break;
            }
        }

        long long ans = 0;
        for(int j = i; j < n;++j){
            if(!isdigit(s[j])){
                break;
            }

            ans = ans * 10 + (Positive ? (s[j] - '0') : -(s[j] - '0'));

            if(ans > INT_MAX){
                return INT_MAX;
            }
            else if(ans < INT_MIN){
                return INT_MIN;
            }
        }

        return (int) ans;
    }
};