我現(xiàn)在在做一個叫《leetbook》的開源書項目,把解題思路都同步更新到github上了装哆,需要的同學(xué)可以去看看
地址:https://github.com/hk029/leetcode
這個是書的地址:https://hk029.gitbooks.io/leetbook/
008. String to Integer (atoi) [E]
題目
Implement atoi to convert a string to an integer.
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.
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.
思路
這題也比較好做定嗓,關(guān)鍵是要考慮挺多東西,我也是提交了好多次才發(fā)現(xiàn)有這么多要考慮的地方凌简。
- 開頭的空格
- 正負符號的處理
- 溢出處理
- 非法輸入
開頭空格處理:
while(str[i] == " ") i++;
正負號的處理:我覺得yuruofeifei這個解決方案簡直贊
if (str[i] == '-' || str[i] == '+') {
sign = 1 - 2 * (str[i++] == '-');
}
……
return base * sign;
溢出處理(可以參考上一道題):
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > INT_MAX%10)) {
if (sign == 1) return INT_MAX;
else return INT_MIN;
}
非法輸入:其實只用過濾就行了
while (str[i] >= '0' && str[i] <= '9') {
……
}
代碼
我的代碼号醉,不夠簡潔辛块,可以參考yuruofeifei的代碼,在下面
class Solution {
public:
int myAtoi(string str) {
long tmp=0;
bool neg;
int i = 0;
while(str[i] == ' ') i++; //讀掉空格
neg = str[i] == '-'?1:0;
for(i = i+ (neg || str[i] == '+');i < str.length();i++) //如果是- 或 + i+1跳過符號
{
if(str[i] - '0' >= 0 && str[i] - '0' < 10) //過濾非法輸入
{
tmp *= 10;
tmp += (str[i] - '0');
if(tmp >= INT_MAX && !neg) //溢出判斷
{
tmp = INT_MAX;
break;
}
if(tmp -1 >= INT_MAX && neg) //除了符號线椰,INT_MAX和INT_MIN只差1
{
tmp = INT_MIN;
break;
}
}
else break;
}
if(neg) return -tmp;
return tmp;
}
};
yuruofeifei的代碼
int myAtoi(string str) {
int sign = 1, base = 0, i = 0;
while (str[i] == ' ') { i++; }
if (str[i] == '-' || str[i] == '+') {
sign = 1 - 2 * (str[i++] == '-');
}
while (str[i] >= '0' && str[i] <= '9') {
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
if (sign == 1) return INT_MAX;
else return INT_MIN;
}
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}