-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution005.java
58 lines (47 loc) · 1.52 KB
/
Solution005.java
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
52
53
54
55
56
57
58
package algorithm.tmop;
/**
* @author: mayuan
* @desc: 字符串转换成整数
* 时间复杂度: O(n)
* 空间复杂度: O(1)
* @date:
*/
public class Solution005 {
public static void main(String[] args) {
final String str1 = "123";
final String str2 = "-123";
final String str3 = "-12aaa3";
final String str4 = "12399999999999999999";
System.out.println(strToInt(str1));
System.out.println(strToInt(str2));
// System.out.println(strToInt(str3));
System.out.println(strToInt(str4));
}
public static int strToInt(String str) {
if (null == str || 0 >= (str = str.trim()).length()) {
throw new IllegalArgumentException();
}
long number = 0L;
int sign = 1;
int start = 0;
if ('+' == str.charAt(0)) {
start = 1;
} else if ('-' == str.charAt(0)) {
start = 1;
sign = -1;
}
for (int i = start; i < str.length(); ++i) {
char c = str.charAt(i);
if ('0' > c || '9' < c) {
throw new NumberFormatException("字符串非法");
}
number = number * 10 + (c - '0');
if (sign * number > Integer.MAX_VALUE) {
throw new NumberFormatException("超出int表示范围");
} else if (sign * number < Integer.MIN_VALUE) {
throw new NumberFormatException("超出int表示范围");
}
}
return (int) (number * sign);
}
}