forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring-to-integer-atoi.java
More file actions
36 lines (36 loc) · 984 Bytes
/
string-to-integer-atoi.java
File metadata and controls
36 lines (36 loc) · 984 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
/**
* 8. 字符串转换整数 (atoi)
* https://leetcode-cn.com/problems/string-to-integer-atoi/
*
*/
class Solution {
public int myAtoi(String s) {
char[] chars = s.toCharArray();
int len = chars.length;
int index = 0;
while (index < len && chars[index] == ' '){
index++;
}
if (index == len) return 0;
int sign = 1;
char firstChar = chars[index];
if (firstChar == '-') {
index++;
sign = -1;
} else if (firstChar == '+') {
index++;
}
int res = 0, last = 0;
while (index < len) {
char c = chars[index];
if (c < '0' || c > '9') break;
int tem = c - '0';
last = res;
res = res * 10 + tem;
if (last != res / 10)
return (sign == (-1)) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
index++;
}
return res * sign;
}
}