8. 字符串转换整数 (atoi)

执行用时:1 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:41.5 MB, 在所有 Java 提交中击败了11.09% 的用户

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
class Solution {
public int myAtoi(String s) {
char[] chars = s.trim().toCharArray();
if (chars.length == 0) {
return 0;
}
int boundary = Integer.MAX_VALUE / 10;
int sum = 0;
int start = 1;
int neg = 1;
if (chars[0] == '-') {
neg = -1;
} else if (chars[0] != '+') {
start = 0;
}
for (int i = start; i < chars.length; i++) {
if (chars[i] < '0' || chars[i] > '9') break;
if (sum > boundary || sum == boundary && chars[i] > '7') {
return neg == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
sum = sum * 10 + (chars[i] - '0');
}
return neg*sum;
}
}

执行用时:1 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:41.2 MB, 在所有 Java 提交中击败了34.40% 的用户

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
class Solution {
public int strToInt(String str) {
if (str.isEmpty()) {
return 0;
}
boolean neg = false;
int start = 0;
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ' ') {
if (str.charAt(i) == '-') {
start = i + 1;
neg = true;
break;
} else if (str.charAt(i) == '+') {
start = i + 1;
break;
} else if (str.charAt(i) - '0' >= 0 && str.charAt(i) - '0' <= 9) {
start = i;
break;
} else {
return 0;
}
}
}
for (int i = start; i < str.length(); i++) {
if (str.charAt(i) == '0') {
continue;
}
start = i;
break;
}
for (int i = start; i < str.length(); i++) {
int t = 0;
if (str.charAt(i) - '0' >= 0 && str.charAt(i) - '0' <= 9) {
t = str.charAt(i) - '0';
if (!neg) {
if(sum > (Integer.MAX_VALUE-t)/10) return Integer.MAX_VALUE;
sum = sum * 10 + t;
} else {
if(sum < (Integer.MIN_VALUE+t)/10) return Integer.MIN_VALUE;
sum = sum * 10 - t;
}
} else {
break;
}
}
return sum;
}
}

8. 字符串转换整数 (atoi)
https://pisces34.github.io/2022/03/16/leetcode/8/
发布于
2022年3月16日
许可协议