Tuesday, August 4, 2015

突击刷题: atoi, string to integer

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
    /**
     * @param str: A string
     * @return An integer
     */
    int atoi(string str) {
        // write your code here
        const char* s=str.c_str();
        int result=0;
        static int CHECK= INT_MAX/10;
        static int MAX_CHECK = INT_MAX%10;
        static int MIN_CHECK=  MAX_CHECK+1;
        bool sign=false;
        while(isspace(*s))
            s++;
        if (*s=='+'||*s=='-'){
            if (*s=='-')
                sign=true;
            s++;
        }
        while(isdigit(*s)){
            int val=*s-'0';
            if (sign && (result>CHECK || result == CHECK && val>=MIN_CHECK))
                return INT_MIN;
            if (!sign && (result>CHECK || result == CHECK && val>=MAX_CHECK))
                return INT_MAX;
            result=10*result+val;
            s++;
        }
        return sign?-result:result;
    }
};

No comments:

Post a Comment