String to Integer (atoi)

Implement atoi to convert a string to an integer.
實現(xiàn)atoi,把一個字符串轉(zhuǎn)換為整數(shù)。
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
提示:謹慎思考所有可能的輸入情況,如果你想要調(diào)整,請不要看下文的提示,向自己提問什么是可能的輸入。
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
注意事項:這個問題制定的很模糊(沒有給定輸入情況),解題之前,你要搜集所有的輸入要求。

解:

需要考慮的情況:
1.知道第一個非空字符,丟棄之前的字符。從這個字符,確定返回值的正負值,如" -123",應(yīng)把之前的空格過濾掉,判斷是不是負數(shù)。
2.在數(shù)字之后,可以有其他類型的字符,這時應(yīng)忽略之后的字符如:"1234ab34a"應(yīng)該忽略"ab34a"。
3.如果該字符串的首個非空字符,不知構(gòu)成整數(shù)的字符,或者字符都是空格字符,則不進行轉(zhuǎn)換,返回值為0.
4.如果返回的正確值超出int的范圍返回INT_MAX或者INT_MIN.
參考代碼如下(C++)
class Solution { public: int myAtoi(string str) { long result = 0; bool negative = false; int i = str.find_first_not_of(' '); if (str[i] == '-') negative = true,i++; else if (str[i] == '+') i++; for (int n = i; i - n <= 10 && isdigit(str[i]); i++) result = result * 10 + (str[i]-'0'); if (negative) result = -result; return (result > INT_MAX ? INT_MAX : (result < INT_MIN ? INT_MIN : result)); } };
時間復(fù)雜度O(n),空間復(fù)雜度O(1).

附:

看到一個極簡的代碼,用了c++的stringstream 特性,有投機取巧之嫌。
class Solution { public: int myAtoi(string str) { int out = 0; stringstream ss( str ); ss >> out; return out; } };

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容