-
Notifications
You must be signed in to change notification settings - Fork 0
/
0008.string-to-integer.cpp
95 lines (73 loc) · 1.65 KB
/
0008.string-to-integer.cpp
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <climits>
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int myAtoi(string str)
{
int i = 0;
int syb = 1;
int ret = 0;
while (str[i] == ' ')
i++;
if (str[i] != '+' && str[i] != '-' && (str[i] < '0' && str[i] > '9'))
return 0;
if (str[i] == '-') {
syb = -1;
i += 1;
} else if (str[i] == '+') {
i += 1;
}
while (str[i] >= '0' && str[i] <= '9' && i < str.size()) {
if (syb == 1 && (ret > INT32_MAX / 10 || (ret == INT32_MAX / 10 && str[i] > '6')))
return INT32_MAX;
if (syb == -1 && (ret > INT32_MAX / 10 || (ret == INT32_MAX / 10 && str[i] > '7')))
return INT32_MIN;
ret = ret * 10 + (str[i++] - '0');
}
return syb * ret;
}
};
void test(string str)
{
Solution so;
int atoi;
cout << "str: " << str << endl;
atoi = so.myAtoi(str);
cout << "atoi: " << atoi << endl;
}
int main()
{
string str;
str = "43";
test(str);
str = "+43";
test(str);
str = "-43";
test(str);
str = "";
test(str);
str = " ";
test(str);
str = " +123ads";
test(str);
str = " -123ads";
test(str);
str = " + 345 fds";
test(str);
str = " we can 123";
test(str);
str = " +we can 3";
test(str);
str = " 23456789876543";
test(str);
str = " -23456789876543";
test(str);
str = "-2147483648";
test(str);
str = "2147483648";
test(str);
cout << "press enter to continue" << endl;
cin.get();
}