LeetCode: String to Integer (atoi) [E]——正負號處理

我現在在做一個叫《leetbook》的開源書項目,把解題思路都同步更新到github上了,需要的同學可以去看看
地址: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.

思路

這題也比較好做,關鍵是要考慮挺多東西,我也是提交了好多次才發現有這么多要考慮的地方。

  • 開頭的空格
  • 正負符號的處理
  • 溢出處理
  • 非法輸入

開頭空格處理:

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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容