Skip to content

Commit a404d8d

Browse files
committed
Create 8. String to Integer(atoi).cpp
1 parent 102dd33 commit a404d8d

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

8. String to Integer(atoi).cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public:
3+
int myAtoi(string str) {
4+
long long res = 0;
5+
int end = str.find_first_not_of(' ', 0);
6+
if(end == str.length() || (str[end] != '+' && str[end] != '-' && !isdigit(str[end])))
7+
return 0;
8+
int sign = str[end] == '-' ? -1 : 1;
9+
if(!isdigit(str[end])) end++;
10+
while(isdigit(str[end])){
11+
res = res * 10 + (str[end++] - '0') * sign;
12+
if(res >= INT_MAX) return INT_MAX;
13+
else if(res <= INT_MIN) return INT_MIN;
14+
}
15+
return res;
16+
}
17+
};

0 commit comments

Comments
 (0)