Skip to content

Commit def822a

Browse files
committed
refine
1 parent 6aab717 commit def822a

File tree

1 file changed

+25
-26
lines changed

1 file changed

+25
-26
lines changed

StringtoIntegerAtoi.java

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -34,38 +34,37 @@
3434

3535
public class StringtoIntegerAtoi {
3636
public int atoi(String str) {
37-
int len = str.length();
38-
if (len == 0)
37+
str = str.trim();
38+
int length = str.length();
39+
if (length == 0)
3940
return 0;
40-
int ret = 0;
41-
boolean signal = true;
4241
int i = 0;
43-
while (i < len && str.charAt(i) == ' ') {
42+
boolean minus = false;
43+
if (str.charAt(0) == '-') {
44+
minus = true;
4445
i++;
45-
}
46-
if (i < len && str.charAt(i) == '-') {
47-
signal = false;
48-
i++;
49-
} else if (i < len && str.charAt(i) == '+') {
46+
} else if (str.charAt(0) == '+') {
5047
i++;
51-
} else if (str.charAt(i) < '0' || str.charAt(i) > '9')
52-
return 0;
53-
int count = 0;
54-
while (i < len && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
55-
if (signal) {
56-
if (count == 10
57-
|| (count == 9 && ret == 214748364 && str.charAt(i) >= '7'))
58-
return Integer.MAX_VALUE;
59-
ret = ret * 10 + (str.charAt(i) - '0');
48+
}
49+
long MIN_VALUE = Integer.MIN_VALUE;
50+
long MAX_VALUE = Integer.MAX_VALUE;
51+
long num = 0;
52+
boolean finished = false;
53+
for (; i < length && !finished; i++) {
54+
char c = str.charAt(i);
55+
if (c >= '0' && c <= '9') {
56+
num *= 10;
57+
num += c - '0';
6058
} else {
61-
if (count == 10
62-
|| (count == 9 && ret == -214748364 && str.charAt(i) >= '8'))
63-
return Integer.MIN_VALUE;
64-
ret = ret * 10 - (str.charAt(i) - '0');
59+
finished = true;
60+
}
61+
if (minus && 0 - num < MIN_VALUE) {
62+
return Integer.MIN_VALUE;
63+
}
64+
if (!minus && num > MAX_VALUE) {
65+
return Integer.MAX_VALUE;
6566
}
66-
i++;
67-
count++;
6867
}
69-
return ret;
68+
return minus ? new Long(0 - num).intValue() : new Long(num).intValue();
7069
}
7170
}

0 commit comments

Comments
 (0)