-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsolution.cc
More file actions
76 lines (70 loc) · 1.87 KB
/
solution.cc
File metadata and controls
76 lines (70 loc) · 1.87 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
#include<iostream>
using namespace std;
class Solution {
public:
int atoi(const char *str) {
int neg = 3;
int i = 0, lens = strlen(str);
if (lens <= 0){
return 0;
}
for(i = 0; i<lens; i++) {
int c = str[i];
if (c == ' ') {
continue;
}
if (c == '+' || c == '-' || isdigit(c)){
break;
}
return 0;
}
if (str[i] == '-') {
neg = -1;
}
if (str[i] == '+' || str[i] == '-') {
i++;
}
int ret = 0;
for (; i<lens; i++){
int c = str[i];
if (str[i] == ' '){
break;
}
if (!isdigit(c)){
break;
}
c = c-'0';
if (ret > 214748364){
if (neg == -1){
return -2147483648;
}
return 2147483647;
}
else if (ret == 214748364 && c > 7) {
if (neg == -1){
return -2147483648;
}
return 2147483647;
}
ret = ret * 10 + c;
}
if (neg == -1){
ret = -ret;
}
return ret;
}
};
int main(){
char* arr[] = {"1", "+1", "-1", "-+1", "+-1", "0", "9876543210", "-9876543210", " -0012a42"};
int index = 0;
Solution s;
while (index < sizeof(arr)/sizeof(char *)) {
cout<<s.atoi(arr[index])<<endl;
index++;
}
string str;
while (cin>>str) {
cout<<s.atoi(str.c_str())<<endl;
}
return 0;
}