Skip to content

Commit 457dda2

Browse files
authored
Update and rename String to Integer(atoi).java to String to Integer (atoi).java
1 parent 3e693f3 commit 457dda2

File tree

2 files changed

+30
-23
lines changed

2 files changed

+30
-23
lines changed

Medium/String to Integer (atoi).java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int myAtoi(String s) {
3+
int idx = 0;
4+
int n = s.length();
5+
while (idx < n && s.charAt(idx) == ' ') {
6+
idx++;
7+
}
8+
int sign = 1;
9+
if (idx < n && (s.charAt(idx) == '-' || s.charAt(idx) == '+')) {
10+
sign = s.charAt(idx) == '-' ? -1 : 1;
11+
idx++;
12+
}
13+
if (idx == n || !Character.isDigit(s.charAt(idx))) {
14+
return 0;
15+
}
16+
while (idx < n && s.charAt(idx) == '0') {
17+
idx++;
18+
}
19+
int number = 0;
20+
while (idx < n && Character.isDigit(s.charAt(idx))) {
21+
int digit = Character.getNumericValue(s.charAt(idx));
22+
if ((number > Integer.MAX_VALUE / 10) || (number == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) {
23+
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
24+
}
25+
number = number * 10 + digit;
26+
idx++;
27+
}
28+
return number * sign;
29+
}
30+
}

Medium/String to Integer(atoi).java

Lines changed: 0 additions & 23 deletions
This file was deleted.

0 commit comments

Comments
 (0)