-
Notifications
You must be signed in to change notification settings - Fork 0
/
8.string to integers.cpp
73 lines (66 loc) · 1.9 KB
/
8.string to integers.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
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
class Solution {
public:
int myAtoi(string str) {
double result = 0;
//storing the operator's position
int flagPos = -1;
int flagNag = -1;
int j = 0;
for( j = 0;j<str.size();j++){
if(str[j] =='+')
{flagPos = j;break;}
if(str[j] =='-')
{flagNag = j;break;}
}
j = j+1;
if(j ==str.size())
return 0;
if(flagPos !=-1&&flagNag !=-1)
return 0;
if(str[j]<48||str[j]>57)
return 0;
if(flagNag == -1){
if(j-flagPos !=1&&flagPos!=-1) return 0;
for(int i = j;i<str.size();i++){
if(str[i]>=48&&str[i]<=57){
if(result!=0){
result *= 10;
result += (str[i]-48);
if(TestIfOutBound(result))
return OutBound(result);}
else{
result +=str[i]-48;}
}else{
return result;
}
}
}else{
if(j-flagNag!=1) return 0;
for(int i = j;i<str.size();i++){
if(str[i]>=48&&str[i]<=57){
if(result!=0){
result *= 10;
result -=(str[i]-48);
if(TestIfOutBound(result))
return OutBound(result);}
else{
result -=(str[i]-48);}
}else{
return result;}
}
}
return result;
}
int OutBound(double x){
if(x>INT_MAX)
return INT_MAX;
if(x<INT_MIN)
return INT_MIN;
return 0;
}
int TestIfOutBound(double x){
if(x>INT_MAX||x<INT_MIN)
return 1;
return 0;
}
};