【Leetcode】String to Integer

題目:

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.

spoilers alert... click to show requirements for atoi.

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.


解題思路:需要注意對越界進行判斷的方法,這裏採用的方法是判斷已有數字串是否大於INT_MAX/10,如果是,那麼加上現在字符中的單個數字以後必然越界;另一種越界的可能性是已有數字串等於INT_MAX/10,而待加的單個數字大於INT_MAX%10。還需要設置一個sign標誌來進行正負輸出。


代碼:

class Solution {
public:
    int atoi(const char *str) {
        if(str==nullptr)return 0;
        int trans_num=0;
        int sign=1;
        while(*str!='\0'){
            if(isspace(*str)){
                str++;
                continue;
            }
            if(isalpha(*str))return 0;
            if(isdigit(*str)||*str=='-'||*str=='+'){
                if(isdigit(*str))trans_num=*str-'0';
                if(*str=='-')sign=-1;
                str++;
                while(*str!='\0'){
                    if(isdigit(*str)){
                        if(trans_num>INT_MAX/10||(trans_num==INT_MAX/10&&(*str-'0')>(INT_MAX%10)))return sign==-1?INT_MIN:INT_MAX;
                        trans_num=trans_num*10+(*str-'0');
                        str++;
                        continue;
                    }else{
                        break;
                    }
                }
                break;
            }
            str++;
        }
        return trans_num*sign;
    }
};


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