[LeetCode] String to Integer (atoi)

Implement atoi to convert a string to an integer.

class Solution {
public:
    int atoi(const char *str) {
        int i = 0,flag = 1;
        long long ans = 0;
        while(str[i] == ' ') i ++;
        if(str[i] == '+') {
            if(str[i + 1] == '-')
                return 0;
            i ++;
        }
        if(str[i] == '-'){
            i ++;
            flag = -1;
        }
        for(;str[i] != '\0';i ++){
            if(str[i] >= '0' && str[i] <= '9'){
                ans =  flag * (str[i] - '0') + ans * 10;
                if(ans > INT_MAX)
                    return INT_MAX;
                if(ans < INT_MIN)
                    return INT_MIN;
            }
            else
                break;
        }
        return ans;
    }
};


發佈了152 篇原創文章 · 獲贊 0 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章