[leetcode_8] String to Integer (atoi)

这个题真心想我理解了读题的重要性。
我就疯狂的WA啊。。。
题意很简单:
读入一个串,转化为 int,如果越界,输出边界值。
但是需要注意 + 和 – 符号。
还需要值得注意的是:
先清空前面的所有空格,然后遇到第一个不是空格的字符开始识别,一直识别到不能识别为止。
但是特殊情况是:如果是‘ a123123123’这个串需要返回0。
算法和数据结构不难,附上代码:

 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;
    }
};
Licensed under CC BY-NC-SA 4.0