leetcode008: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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

問題分析

和leetcode007的題目用到的點基本相同,只是有些情況在運行測試後發現的,如“ +5df”這樣的字符串是5,要考慮到,而不是返回錯誤,ok,直接上代碼。

代碼

class Solution {
public:
    int atoi(string str) {
        int i = 0;
        while (i < str.length() && str[i] == ' ')   { i++; }
        str = str.substr(i);
        if (str.length() <= 0) return 0;
        char arr[13];//選擇13的目的是int型10進制最大值位數爲10位,加上符號位爲11位,防止溢出。
        int flag = 0;
        for (i = 0; i < 12 && i < str.length(); i++)
        {
            if (i == 0 && (str[i] == '-' || str[i] == '+') || str[i] >= '0' && str[i] <= '9')   arr[i] = str[i];
            else break;
        }
        arr[i] = '\0';
        int len = strlen(arr);
        if (!len || len == 1 && (arr[0] == '+' || arr[0] == '-')) return 0;
        long long k;
        sscanf(arr, "%lld", &k);
        if (k > INT_MAX) k = INT_MAX;
        if (k < INT_MIN) k = INT_MIN;
        return k;
    }
};
發佈了60 篇原創文章 · 獲贊 8 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章