-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoi.java
More file actions
37 lines (33 loc) · 998 Bytes
/
atoi.java
File metadata and controls
37 lines (33 loc) · 998 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
37
public class Solution {
public int atoi(String str) {
// Start typing your Java solution below
// DO NOT write main() function
// string start with -
// string is overflow the Integer.MAX_VALUE
if(str.length() == 0) return 0;
int right = str.length() - 1;
int res = 0;
int digit = 1;
if(right == 0){
return str.charAt(right) - '0';
}
while(right >= 0){
char c = str.charAt(right);
//System.out.println(res);
if(c == '+') {
right--;
} else if (c == '-'){
res *= -1;
right--;
} else if (('0' <= c) && (c <= '9')) {
//System.out.println(c);
res += ((c - '0') * digit);
digit *= 10;
right--;
} else {
right--;
}
}
return res;
}
}