Skip to content

Commit 8f61cb4

Browse files
committed
8.字符串转换整数(atoi)
1 parent a8fd700 commit 8f61cb4

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
3. 无重复字符的最长子串
44
4. 寻找两个有序数组的中位数
55
5. 最长回文子串
6+
8. 字符串转换整数 (atoi)
67
11. 盛最多水的容器
78
15. 三数之和
89
17. 电话号码的字母组合

leetcode_Java/Solution0008.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// 8. 字符串转换整数 (atoi)
2+
3+
4+
/*
5+
1、遍历去掉空格
6+
2、判断是否有+-符号,有则记录sign
7+
3、遍历数字,如果算上当前数字后超过整型最大值,则根据sign标志直接返回结果,否则更新结果将当前数字加入最低位
8+
if语句另一写法 if ((long) res * 10 + digit > Integer.MAX_VALUE) {}
9+
4、根据sign标志返回结果
10+
*/
11+
class Solution {
12+
public int myAtoi(String s) {
13+
int n = s.length(), res = 0, index = 0, sign = 1;
14+
char[] array = s.toCharArray();
15+
while (index < n && array[index] == ' ') {
16+
index++;
17+
}
18+
if (index < n && (array[index] == '-' || array[index] == '+')) {
19+
sign = array[index++] == '-' ? -1 : 1;
20+
}
21+
while (index < n && array[index] >= '0' && array[index] <= '9') {
22+
int digit = array[index++] - '0';
23+
if (res > (Integer.MAX_VALUE - digit) / 10) {
24+
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
25+
}
26+
res = res * 10 + digit;
27+
}
28+
return res * sign;
29+
}
30+
}

0 commit comments

Comments
 (0)