-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8.string-to-integer-atoi.cpp
51 lines (38 loc) · 1.12 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
42
43
44
45
46
47
48
49
50
51
class Solution {
public:
int myAtoi(string s) {
long long num = 0;
int size = s.size();
int i = 0;
bool negative=false;
while(i<size && s[i] == ' ')
i++;
// cout<<"i:"<<i<<endl;
if(i<size-1 && (s[i] == '+' || s[i] == '-')){
if(s[i] == '-' )
negative = true;
i++;
}
// else if(i<size && ((int)s[i]<48 || (int)s[i]>57))
// return 0;
while(i<size && ((int)s[i]>=48 && (int)s[i]<=57)){
// cout<<s[i]<<" : Now"<<endl;
num *= 10;
num+=(int)s[i] - 48;
i++;
if(num > INT_MAX)
break;
}
if(num > INT_MAX){
num = INT_MAX;
if(negative){
num+=1;
num*=-1;
return num;
}
}
if(negative)
return (int)num*-1;
return (int)num;
}
};