-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringToInteger.java
More file actions
48 lines (38 loc) · 1.11 KB
/
Copy pathStringToInteger.java
File metadata and controls
48 lines (38 loc) · 1.11 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
// Link: https://leetcode.com/problems/string-to-integer-atoi/description/
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;
if (sign * res <= INT_MIN) {
return INT_MIN;
}
if (sign * res >= INT_MAX) {
return INT_MAX;
}
i++;
}
return (int)(res * sign);
}
}