Skip to content

Commit 8ef30f8

Browse files
authored
Merge pull request doocs#68 from bluesword12350/master
008. String to Integer (atoi) (java)
2 parents 646dac9 + 265dd36 commit 8ef30f8

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int myAtoi(String str) {
3+
int len = str.length();
4+
if (len == 0) return 0;
5+
char[] cs = str.toCharArray();
6+
int i = 0;
7+
while (i < len && cs[i] == ' ') i++;
8+
if (i==len) return 0;
9+
char c1 = cs[i];
10+
int sig = 1;
11+
if ((c1 > '9' || c1 < '0')) {
12+
if (c1 == '-') {
13+
sig = -1;
14+
i++;
15+
} else if (c1 == '+') {
16+
i++;
17+
} else return 0;
18+
}
19+
long v = 0,sv = 0;
20+
for (; i < len; i++) {
21+
char c = cs[i];
22+
if (c < '0' || c > '9') break;
23+
v = v * 10 + (c - '0');
24+
sv = v * sig;
25+
if (sv > Integer.MAX_VALUE) return Integer.MAX_VALUE;
26+
else if (sv < Integer.MIN_VALUE) return Integer.MIN_VALUE;
27+
}
28+
return (int) sv;
29+
}
30+
}

0 commit comments

Comments
 (0)