-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
31 lines (24 loc) · 800 Bytes
/
Solution.java
File metadata and controls
31 lines (24 loc) · 800 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
class Solution {
public int myAtoi(String s) {
if (s == null || s.length() == 0) return 0;
s = s.trim();
if (s.isEmpty()) return 0;
int index = 0;
int sign = 1;
int result = 0;
int n = s.length();
if (index < n && (s.charAt(index) == '+' || s.charAt(index) == '-')) {
sign = (s.charAt(index) == '-') ? -1 : 1;
index++;
}
while (index < n && Character.isDigit(s.charAt(index))) {
int digit = s.charAt(index) - '0';
if (result > (Integer.MAX_VALUE - digit) / 10) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
result = result * 10 + digit;
index++;
}
return result * sign;
}
}