-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.java
39 lines (37 loc) · 1.28 KB
/
Solution.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
package _008;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/04/23
* desc :
* </pre>
*/
public class Solution {
public int myAtoi(String str) {
int i = 0, ans = 0, sign = 1, len = str.length();
while (i < len && str.charAt(i) == ' ') ++i;
if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) {
sign = str.charAt(i++) == '+' ? 1 : -1;
}
for (; i < len; ++i) {
int tmp = str.charAt(i) - '0';
if (tmp < 0 || tmp > 9)
break;
if (ans > Integer.MAX_VALUE / 10 || ans == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 < tmp)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
else
ans = ans * 10 + tmp;
}
return sign * ans;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.myAtoi(" +1"));
System.out.println(solution.myAtoi(" -1"));
System.out.println(solution.myAtoi(""));
System.out.println(solution.myAtoi("a1"));
System.out.println(solution.myAtoi("100000000000000000000"));
System.out.println(solution.myAtoi("-100000000000000000000"));
}
}