實現atoi將字符串轉換為整數。
提示:仔細考慮所有可能的輸入案例。如果你想挑戰,請不要在下面看到,問問自己可能輸入的情況是什么。
注意:它是為這個問題指定模糊的(即,沒有給定的輸入規格)。你有責任把所有的輸入需求收集到前面。
【別人的總結】
照著要求寫代碼,可以總結如下:
- 字串為空或者全是空格,返回0;
- 字串的前綴空格需要忽略掉;
- 忽略掉前綴空格后,遇到的第一個字符,如果是‘+’或‘-’號,繼續往后讀;如果是數字,則開始處理數字;如果不是前面的2種,返回0;
- 處理數字的過程中,如果之后的字符非數字,就停止轉換,返回當前值;
- 在上述處理過程中,如果轉換出的值超出了int型的范圍,就返回int的最大值或最小值。
class Solution {
public:
int myAtoi(string str) {
long long result = 0;
int flag = 1;//負號標志
size_t i = 0,len = str.size();
//跳過空白
while (str[i] == ' '){ ++i; }
//查看 + -
if (str[i] == '-' || str[i] == '+'){
flag = (str[i++] == '+') ? 1 : -1;
}
while (str[i] <= '9' && str[i] >= '0')
{
//每個字符都是以ascii碼讀取,所有需要減去0的ascii值:48
result = result * 10 +(str[i++]-'0');
if (result >= INT_MAX&&flag ==1){
return INT_MAX;
}
else if (-result <= INT_MIN&&flag == -1)
{
return INT_MIN;
}
}
return result*flag;
}
};
【別人家的代碼】
class Solution {
public:
int myAtoi(string str) {
long long res = 0; // string could be greater than max long long ;
int i = 0;
bool sign = true;
// 1) step trim out whitespace;
while (str[i] == ' ' && i < str.length()) {
i++;
}
// 2) deal with sign;
if (str[i] == '+' || str[i] == '-') {
sign = (str[i] == '+') ? true : false;
i++;
}
// 3) compute value;
while (i < str.length()) {
//compute current value;
if (str[i] >= '0' && str[i] <= '9') {
res = res*10 + str[i]- '0';
if (res - INT_MAX >= 1) { //overflow;
break;
}
i++;
} else {
break;
}
}
if (res - INT_MAX >= 1) {
if (sign) {
return INT_MAX;
}
return INT_MIN;
}
res = sign ? res : (-1)*res;
return res;
}
};