LeetCode 8. String to Integer (atoi)html
字符串轉換成數字。code
我的認爲題目並無徹底講清楚題意。最初覺得須要考慮多種狀況,小數啊指數啊什麼的,後面發現不是這樣的,這題只要關注字符數字問題以及範圍問題。htm
1.跳過空格字符;blog
2.判斷正負號;ip
3.判斷數字,順便判斷範圍。leetcode
注意正負號和數字要連續,不能斷;數字以後再出現非數字字符,直接返回,後面的字符補在理會。字符串
class Solution { public: int myAtoi(string str) { if (str.empty()) return 0; int sign = 1, i = 0, len = str.size(); int res = 0; while (i < len && str[i] == ' ') i++; if (str[i] == '+' || str[i] == '-') sign = (str[i++]=='+' ? 1 : -1); while (i < len && str[i] >= '0' && str[i] <= '9') { if (res > INT_MAX/10 || (res == INT_MAX/10 && str[i] >= '8')) return sign==1 ? INT_MAX : INT_MIN; res = res*10 + (str[i]-'0'); i++; } return sign * res; } };
LeetCode All in One題解彙總(持續更新中...)get
本文版權歸做者AlvinZH和博客園全部,歡迎轉載和商用,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利.博客