-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8_StringToInteger.cpp
More file actions
60 lines (54 loc) · 1.36 KB
/
8_StringToInteger.cpp
File metadata and controls
60 lines (54 loc) · 1.36 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
class Solution {
public:
int myAtoi(string s) {
bool posOrNeg = true; //assume positive
string tmp = "";
int ans = 0;
int firstIndex = 0;
for(int i = 0; i < s.length(); i++){
if(s.at(i) == ' '){
++firstIndex;
}
else{
break;
}
}
if(firstIndex >= s.length()){
return 0;
}
if(s.at(firstIndex) == '+'){
firstIndex += 1;
}
else if(s.at(firstIndex) == '-'){
posOrNeg = false;
firstIndex += 1;
}
for(int i = firstIndex; i < s.length(); i++){
if(s.at(i) >= '0' && s.at(i) <= '9'){
tmp += s.at(i);
}
else{
break;
}
}
if(tmp == ""){
return 0;
}
for(int i = 0; i < tmp.length(); i++){
int num = tmp.at(i) - '0';
int64_t result = (int64_t)ans * 10;
result += num;
if(posOrNeg && result >= INT_MAX){
return INT_MAX;
}
if(!posOrNeg && (result * -1) <= INT_MIN){
return INT_MIN;
}
ans = result;
}
if(posOrNeg == false){
ans = ans * -1;
}
return ans;
}
};