-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
executable file
·65 lines (61 loc) · 1.66 KB
/
Solution.java
File metadata and controls
executable file
·65 lines (61 loc) · 1.66 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package $008;
/**
* @author Junlan Shuai[shuaijunlan@gmail.com].
* @date Created on 9:23 2017/10/18.
*/
public class Solution {
public int myAtoi(String str) {
int N = str.length();
if (N == 0) {
return 0;
}
boolean isNeg = false, overflow = false;
int i = 0;
while (i < N && str.charAt(i) == ' ') {
i++;
}
if (i == N) {
return 0;
}
if (str.charAt(i) == '-' || str.charAt(i) == '+') {
isNeg = (str.charAt(i) == '-');
i++;
}
int n = 0;
while (i < N) {
char c = str.charAt(i);
if (c > '9' || c < '0') {
break;
}
int digit = c - '0';
if ((Integer.MAX_VALUE - digit) / 10 >= n){
n = 10 * n + digit;
}
else {
overflow = true;
break;
}
i++;
}
int result = 0;
if (isNeg) {
result = overflow ? Integer.MIN_VALUE : -n;
} else {
result = overflow ? Integer.MAX_VALUE : n;
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
String a = "-1234567";
System.out.println(solution.myAtoi(a));
String b = " - dfa45fasdf";
System.out.println(solution.myAtoi(b));
String c = "-a1 232 13";
System.out.println(solution.myAtoi(c));
String d = "100 - 123";
System.out.println(solution.myAtoi(d));
String e = "+-2";
System.out.println(solution.myAtoi(e));
}
}