-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString_To_Integer.cc
More file actions
46 lines (42 loc) · 842 Bytes
/
String_To_Integer.cc
File metadata and controls
46 lines (42 loc) · 842 Bytes
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
//Implement atoi to convert a string to an integer.
#include <vector>
#include <climits>
#include <iostream>
using namespace std;
class Solution {
public:
int atoi(const char *str) {
while (*str == ' ') {
++ str;
}
int sign = 1;
if (*str == '-') {
sign = -1;
++ str;
}
if (*str == '+') {
++ str;
}
int ret = 0;
while (*str != '\0') {
if (*str < '0' || *str > '9') {
return sign * ret;
}
int d = *str - '0';
if (sign == 1 && (ret > INT_MAX/10 || (ret == INT_MAX/10 && d > INT_MAX%10))) {
return INT_MAX;
}
if (sign == -1 && (ret > -(INT_MIN/10) || (ret == -(INT_MIN/10) && d > -(INT_MIN%10)))) {
return INT_MIN;
}
ret = ret * 10 + d;
++ str;
}
return sign * ret;
}
};
int main() {
Solution sol = Solution();
cout << sol.atoi("-2147483649") << endl;
return 0;
}