-
Notifications
You must be signed in to change notification settings - Fork 1
/
8. String to Integer (atoi).cpp
41 lines (40 loc) · 1.14 KB
/
8. String to Integer (atoi).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
class Solution {
public:
int myAtoi(string s) {
int n = s.size();
bool isPos = true;
string news = "";
long long ans = 0;
int flag = 0;
int flag2 = 0;
for(int i = 0; i < n; i++) {
if(s[i] == ' ' && flag2 == 0) continue;
else if(s[i] == '+') {
flag2 = 1;
if(news == "" && flag == 0) {isPos = true; flag = 1;}
else break;
}
else if(s[i] == '-') {
flag2 = 1;
if(news == "" && flag == 0) {isPos = false; flag = 1;}
else break;
}
else if(s[i] - '0' <= 9 && s[i] - '0' >= 0) {
flag2 = 1;
news += s[i];
}
else break;
}
if(news.size() == 0) return 0;
ans = news[0] - '0';
for(int i = 1; i < news.size(); i++) {
ans = ans*10 + (news[i] - '0');
if(ans > INT_MAX) {
if(isPos) return INT_MAX;
else return INT_MIN;
}
}
if(isPos) return ans;
else return -ans;
}
};