LeetCode: String to Integer

Title : 

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.

需要考虑的因素有:

空格,正负号,越界等。这里对于中间出现非数字字符则是直接忽略后面的所有字符串,

if(!isdigit(c)) break; 
class Solution {
public:

    bool isdigit(char c){
        if (c >= 48 && c <= 57)
            return true;
        else
            return false;
    }
    int atoi(string str){
        long long  ans = 0,res=1;
        bool flag = false;
        char c;
        for(int i=0;i < str.size() ;i++){
            c = str[i];
            if(!flag && (c==' ' || c=='	' || c=='
' || c=='
') ) continue;
            if(!flag && (c=='+' || c=='-') ){
                if(c=='-') res = -1;
                flag = true;
                continue;
            }
            if(!flag && isdigit(c)){
                flag = true;
            }
            if(!isdigit(c)) break;
            ans = ans * 10 + (c-'0');
            //cout<<ans<<' '<<c<<endl;
            if(ans > INT_MAX ){
                break;
            }
        }
        ans *= res;
        if(ans > INT_MAX) ans = INT_MAX;
        else if (ans < INT_MIN ) ans = INT_MIN;
        return (int)ans;
    }
};
原文地址:https://www.cnblogs.com/yxzfscg/p/4419102.html