閱讀299 返回首頁    go 阿裏雲 go 技術社區[雲棲]


[LeetCode]8. 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.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

【題意】

實現atoi函數功能,將字符串轉換為整數。

【分析】

細節題:

要仔細考慮不同的測試用例:

1.     -3445  -> -345

2.    -34hhf67 -> -34

3.    +56 -> 56

4.   ++1 ->  0

5.   ++a -> 0

6.  溢出數據: -2147483649 -> -2147483648

2147483649  -> -2147483647

【代碼】

/*********************************
*   日期:2014-02-05
*   作者:SJF0115
*   題號: String to Integer (atoi)
*   來源:https://oj.leetcode.com/problems/string-to-integer-atoi/
*   結果:AC
*   來源:LeetCode
*   總結:
**********************************/
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <limits.h>
using namespace std;


class Solution {
public:
    int atoi(const char *str) {
        if(str == NULL){
            return 0;
        }
        int n = strlen(str);
        long long result = 0;
        int flag = 1;
        int index = 0;
        //過濾空格
        while(str[index] == ' '){
            index++;
        }
        //判斷是否有正負號
        if(str[index] == '-'){
            flag = -1;
            index++;
        }
        else if(str[index] == '+'){
            flag = 1;
            index++;
        }
        for(int i = index;i < n;i++){
            if(str[i] < '0' || str[i] > '9'){
                break;
            }
            result = result * 10 + (str[i] - '0');
            if(flag == 1 && result > INT_MAX){
                return INT_MAX;
            }
            else if(flag == -1 && -1*result < INT_MIN){
                return INT_MIN;
            }
        }
        return (int)flag * result;
    }
};

int main() {
    Solution solution;
    char *str = "2147483649";
    int result = solution.atoi(str);
    cout<<result<<endl;
    return 0;
}

【代碼2】

class Solution {
public:
    int atoi(const char *str) {
        if(str == NULL){
            return 0;
        }
        int n = strlen(str);
        int result = 0;
        int flag = 1;
        int index = 0;
        //過濾空格
        while(str[index] == ' '){
            index++;
        }
        //判斷是否有正負號
        if(str[index] == '-'){
            flag = -1;
            index++;
        }
        else if(str[index] == '+'){
            flag = 1;
            index++;
        }
        for(int i = index;i < n;i++){
            if(str[i] < '0' || str[i] > '9'){
                break;
            }
            //判斷是否溢出
            if(result > INT_MAX / 10 || (result == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10)){
                return flag == -1?INT_MIN:INT_MAX;
            }
            result = result * 10 + (str[i] - '0');
        }
        return flag * result;
    }
};

【溫故】

/*---------------------------------------
*   日期:2015-05-07
*   作者:SJF0115
*   題目: 8.String to Integer (atoi)
*   網址:https://leetcode.com/problems/string-to-integer-atoi/
*   結果:AC
*   來源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
using namespace std;

class Solution {
public:
    int myAtoi(string str) {
        int size = str.size();
        if(size == 0){
            return 0;
        }//if
        int index = 0;
        // 空格
        while(index < size && str[index] == ' '){
            ++index;
        }//while
        if(index >= size){
            return 0;
        }//if
        // 正負性
        int positive = 1;
        if(str[index] == '-'){
            positive = -1;
            ++index;
        }//if
        else if(str[index] == '+'){
            positive = 1;
            ++index;
        }//else
        long long result = 0;
        for(int i = index;i < size;++i){
            // 無效字符
            if(!isValid(str[i])){
                break;
            }//if
            result = result * 10 + (str[i] - '0');
            // 正數溢出
            if(positive == 1 && result > INT_MAX){
                return  INT_MAX;
            }//if
            // 負數溢出
            if(positive == -1 && -1*result < INT_MIN){
                return  INT_MIN;
            }//if

        }//for
        return positive*(int)result;
    }
private:
    bool isValid(char c){
        if(c >= '0' && c <= '9'){
            return true;
        }//if
        return false;
    }
};

int main() {
    Solution solution;
    string str("  -0012a42");
    cout<<solution.myAtoi(str)<<endl;
}

最後更新:2017-04-03 12:54:57

  上一篇:go 獲取星座的JS函數
  下一篇:go Python查詢MySQL進行遠程采集圖片實例