-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode-8.java
More file actions
36 lines (27 loc) · 839 Bytes
/
Copy pathLeetcode-8.java
File metadata and controls
36 lines (27 loc) · 839 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
32
33
34
35
36
class Solution {
public int myAtoi(String s) {
if(s == null || s.length() == 0) return 0;
final int INT_MAX = Integer.MAX_VALUE;
final int INT_MIN = Integer.MIN_VALUE;
int i = 0;
int n = s.length();
while( i < n && s.charAt(i) == ' ') i++;
if( i == n) return 0;
int sign = 1;
if (s.charAt(i) == '+'){
i++;
}else if (s.charAt(i) == '-'){
sign = -1;
i++;
}
long res = 0;
while ( i < n && Character.isDigit(s.charAt(i))) {
int digit = s.charAt(i) - '0';
res = res * 10 + digit; //key
if ( sign * res <= INT_MIN) return INT_MIN;
if ( sign * res >= INT_MAX) return INT_MAX;
i++;
}
return (int)(res * sign);
}
}