forked from taohi/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoi.cpp
More file actions
36 lines (36 loc) · 936 Bytes
/
Copy pathatoi.cpp
File metadata and controls
36 lines (36 loc) · 936 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
30
31
32
33
34
35
36
class Solution {
public:
int atoi(const char *str) {
int result=0;
int n=strlen(str);
int i=0;
int flag=1;
if(n==0)
return 0;
while(str[i]==' ' && i<n)
i++;
if(str[i]=='-')
{
flag=-1;
i++;
}
else if(str[i]=='+')
i++;
while(i<n)
{
if(str[i]>'9'||str[i]<'0')
{
i++;
break;
}
else
{
if(result>INT_MAX/10||(result==INT_MAX/10 && (str[i]-'0')>INT_MAX%10))
return flag==1?INT_MAX:INT_MIN;
result=result*10+str[i]-'0';
i++;
}
}
return (result*flag);
}
};