-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmyAtoi.cpp
More file actions
29 lines (29 loc) · 719 Bytes
/
myAtoi.cpp
File metadata and controls
29 lines (29 loc) · 719 Bytes
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
class Solution {
public:
int myAtoi(string str) {
int i, ans, sign, backup;
i=0;
while(i<str.length() && str.at(i) == ' ')
i++;
sign = 1; // positive
if(i<str.length() && str.at(i) == '+')
{
i++;
}
else if(i<str.length() && str.at(i) == '-')
{
sign = -1; // negative
i++;
}
ans=0;
while(i<str.length() && isdigit(str.at(i)))
{
backup = ans;
ans = ans*10+(str.at(i)-'0');
if(ans<0 || backup != (ans-(str.at(i)-'0'))/10)
return sign==1?INT_MAX:INT_MIN;
i++;
}
return ans*sign;
}
};