[leetcode_8] String to Integer (atoi)

This problem really taught me the importance of reading the problem statement carefully. I kept getting WA after WA…

The problem is simple: read a string, convert it to an int, and if it overflows, output the boundary value.

However, you need to handle the + and - signs. Also worth noting: first skip all leading spaces, then start parsing from the first non-space character, and continue until you encounter an unrecognizable character.

A special case: for a string like ’ a123123123’, you need to return 0.

The algorithm and data structure are not difficult. Here is the code:

 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
    int atoi(const char *str) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int i;
        for (i = 0; i < strlen(str); i++) {
            if (str[i] != ' ') break;
        }
        if (!((str[i] >= '0' && str[i] <= '9') || (str[i] == '+') || (str[i] == '-')))
            return 0;
        int start = -1;
        int end = -1;
        for (; i < strlen(str); i++) {
            if ((str[i] >= '0' && str[i] <= '9') || (str[i] == '+') || (str[i] == '-')) {
                start = i;
                break;
            }
        }
        if (start == -1)
            return 0;
        for (i = start + 1; i < strlen(str); i++) {
            if (str[i] < '0' || str[i] > '9') {
                end = i - 1;
                break;
            }
        }
        if (i == strlen(str)) {
            end = i - 1;
        }
        int p = 1;
        if (str[start] == '-' || str[start] == '+') {
            if (str[start] == '-')
                p = -1;
            start++;
        }
        double ans = 0;
        int index = 0;
        for (i = end; i >= start; i--) {
            ans += (str[i] - '0') * pow(10.0, index++);
        }
        ans = ans * p;
        if (ans > 2147483647.0)
            return 2147483647;
        if (ans < -2147483648.0)
            return -2147483648;
        return (int)ans;
    }
};