-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringToInteger.cpp
More file actions
82 lines (79 loc) · 2.11 KB
/
Copy pathStringToInteger.cpp
File metadata and controls
82 lines (79 loc) · 2.11 KB
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
#include <string>
#include <stdio.h>
#include <limits.h>
using namespace std;
class Solution {
public:
int atoi(string str) {
bool is_positive = true;
bool is_meat_sign = false;
bool is_start = false;
int res = 0;
int limit = INT_MAX;
for (int i = 0; i < str.length(); i++) {
if (!is_start) {
if (str[i] == ' ') {
continue;
} else {
is_start = true;
}
} else if (str[i] == ' '){
break;
}
if (str[i] == '-') {
is_positive = false;
limit = INT_MIN;
}
bool is_sign = str[i] == '+' || str[i] == '-';
if (is_sign) {
if (is_meat_sign) {
break;
} else {
is_meat_sign = true;
continue;
}
}
if (str[i] >= '0' && str[i] <= '9') {
int val = str[i] - '0';
if (!is_positive) {
val = -val;
}
if (res == 0) {
res = val;
} else {
bool is_not_overflow = (is_positive && (limit - val)/10 >= res) || (!is_positive && res >= (limit-val)/10);
if (is_not_overflow) {
res = res * 10 + val;
} else {
res = limit;
break;
}
}
} else {
break;
}
}
return res;
}
};
int main() {
Solution s;
string str = " 2345";
int val = s.atoi(str);
printf("%d\n", val);
str = " +2345";
val = s.atoi(str);
printf("%d\n", val);
str = " -2345";
val = s.atoi(str);
printf("%d\n", val);
str = " --2345";
val = s.atoi(str);
printf("%d\n", val);
str = " +0 123";
val = s.atoi(str);
printf("%d\n", val);
str = "-2147483648";
val = s.atoi(str);
printf("%d\n", val);
}