Skip to content

Commit 73a875d

Browse files
author
YugenCoder
committed
#8. String to Integer (atoi)
1 parent 770c17f commit 73a875d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

MyAtoI.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package leetcode;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
6+
public class MyAtoI {
7+
8+
public static void main(String[] args) {
9+
MyAtoI atoi = new MyAtoI();
10+
int res = atoi.convertAtoI("-2147483647");
11+
System.out.println(res);
12+
// Test for negatives
13+
// Test for positives
14+
// Test for invalid Entries
15+
}
16+
17+
public int convertAtoI(String str) {
18+
int baseValue = 0;
19+
int sign = 1, idx = 0;
20+
21+
// skip spaces
22+
while (idx < str.length() && str.charAt(idx) == ' ') {
23+
idx++;
24+
}
25+
26+
// check sign
27+
if (idx < str.length() && (str.charAt(idx) == '-' || str.charAt(idx) == '+')) {
28+
sign = str.charAt(idx++) == '+' ? 1 : -1;
29+
}
30+
31+
// calculate integer
32+
while (idx < str.length()) {
33+
int digit = str.charAt(idx) - '0';
34+
if (digit >= 0 && digit <= 9) {
35+
if ((baseValue + digit*0.1) > (Integer.MAX_VALUE/10 + (Integer.MAX_VALUE%10)*0.1)) {
36+
return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
37+
}
38+
baseValue = baseValue * 10 + digit;
39+
} else
40+
break;
41+
idx++;
42+
}
43+
return sign * baseValue;
44+
}
45+
}

0 commit comments

Comments
 (0)