Skip to content

Commit 6e0e3b6

Browse files
author
cpppy
authored
Create 8_String_to_Integer_(atoi).cc
1 parent a2ad811 commit 6e0e3b6

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

8_String_to_Integer_(atoi).cc

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
int myAtoi(string str) {
4+
int result=0;
5+
int k=1;
6+
int count_k=0;
7+
int count_val=0;
8+
int count_dig=0;
9+
for (int i = 0; i<str.size(); ++i){
10+
if(str[i]=='-') {
11+
k=k*(-1);
12+
count_k++;
13+
}
14+
if(str[i]=='+') {
15+
count_k++;
16+
}
17+
if(str[i]!=' ') count_val++;
18+
if(::isdigit(str[i])){
19+
count_dig++;
20+
int tmp=result;
21+
result = result * 10 + (str[i]-'0');
22+
if (k>0&&(result<tmp||count_dig>10)) {
23+
result = 2147483647;
24+
break;
25+
}
26+
if(k<0&&(result<tmp||count_dig>10)){
27+
result= 2147483648;
28+
break;
29+
}
30+
}
31+
if(::isalpha(str[i])||(str[i]==' '&&count_val!=0)) break;
32+
}
33+
if(count_k>1) k=0;
34+
result=result*k;
35+
return result;
36+
}
37+
};

0 commit comments

Comments
 (0)