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
49
50
51
52


#include <iostream>

using namespace std;

int atoi(const char *str) {

    long long val = 0;
    const long long limit = 2147483647;
    bool isNegative = false;

    while (*str != '\0' && *str == ' ') ++str;
    if (*str == '\0') return val;


    if (*str == '-') {
        isNegative = true;
        ++str;
    } else if (*str == '+') {
        isNegative = false;
        ++str;
    }
    
    while (*str != '\0') {
        char c = *str;
        if (c < '0' || c > '9') {
            break;
        }

        val = val*10 + (c-'0');
        if (val > limit) break;
        ++str;
    }
    if (val > limit) {
        if (isNegative) {
            return (-limit-1);
        } else {
            return limit;
        }
    }
    if (isNegative) val = -val;

    return val;
}


int main(int argc, char const *argv[]) {

    char a[] = "2147483648";
    cout << atoi(a) << endl;
    return 0;
}
View Program Text


Test Status