String to Integer (atoi)

一. String to Integer (atoi)

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.

Difficulty:Medium

TIME:18MIN

解法

這道題的的意思是說把字符串轉換爲int類型的數字,轉換的過程要滿足一下幾個要點:

  • 遇到有效字符(+,-,0-9)前的空白符直接跳過
  • 遇到非空白符非有效字符那麼直接輸出已經構造的數字(比如遇到字母)
  • 遇到有效字符後除非遇到數字,不然直接輸出已經構造的數字(比如-+2,輸出0,+2-4輸出2)
int myAtoi(string str) {
    long result = 0;
    int sign = 1;
    bool show = false;  //遇到有效字符的標記,一但遇到有效字符就將該標記置爲true
    for (int i = 0; i < str.size(); i++) {
        if ((str[i] - '0') >= 0 && (str[i] - '0') <= 9) {
            result = 10 * result + str[i] - '0';
            show = true;
        }
        else if (show) //遇到有效字符後,除非是數字,不然就break
            break;
        else if (str[i] == '-') {
            sign = -1;
            show = true;
        }
        else if (str[i] == '+')
            show = true;
        else if (str[i] == '\n' || str[i] == '\r' || str[i] == ' ')
            continue;
        else  //其餘情況一律break
            break;
        if (result * sign > INT32_MAX)
            return INT32_MAX;
        else if (result * sign < INT32_MIN)
            return INT32_MIN;
    }
    return (int)(result * sign);
}

代碼的時間複雜度爲O(n)

總結

這道題並沒有考慮8進制和16進制的情況,不過其實處理起來應該差不了多少。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章