-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_008_string_to_integer_atoi.java
More file actions
51 lines (41 loc) · 1.04 KB
/
Copy path_008_string_to_integer_atoi.java
File metadata and controls
51 lines (41 loc) · 1.04 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* Author: Thong Le
* Date: May 2, 2017
*
* LeetCode 8 - String to Integer (atoi)
*
* Solution Approach:
*
*
*
*/
import java.util.*;
public class _008_string_to_integer_atoi {
public int atoi(String str) {
if (str == null) {
return 0;
}
// a named group is used here: number
Pattern p = Pattern.compile("^\\s*(?<number>[\\+-]?\\d+).*$");
Matcher m = p.matcher(str);
if (m.find()) {
String numberStr = m.group("number");
char signChar = numberStr.charAt(0);
if (signChar >= '0' && signChar <= '9') {
signChar = '+';
}
int number = -1;
try {
number = Integer.parseInt(numberStr);
} catch (Exception e) {
if (signChar == '-') {
number = Integer.MIN_VALUE;
} else {
number = Integer.MAX_VALUE;
}
}
return number;