Skip to content

Commit 65d8e1a

Browse files
authored
Create String to integer(atoi).java
1 parent 26fc63c commit 65d8e1a

File tree

1 file changed

+27
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)