-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringToInteger.java
More file actions
34 lines (32 loc) · 995 Bytes
/
StringToInteger.java
File metadata and controls
34 lines (32 loc) · 995 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* https://leetcode.com/problems/string-to-integer-atoi/
*/
public class StringToInteger {
public int myAtoi(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
String pattern = "^ *([+\\-]?(\\d+))";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
if (m.find()) {
String result = m.group(1);
boolean isNegative = result.charAt(0) == '-';
try {
return Integer.parseInt(result);
} catch (NumberFormatException e) {
if (isNegative) {
return Integer.MIN_VALUE;
} else {
return Integer.MAX_VALUE;
}
}
}
return 0;
}
public static void main(String[] args) {
System.out.println(new StringToInteger().myAtoi(" -42 with words")); // -42
}
}