-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC8_StringToInteger.java
More file actions
31 lines (28 loc) · 892 Bytes
/
LC8_StringToInteger.java
File metadata and controls
31 lines (28 loc) · 892 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
package practise.leetCode;
public class LC8_StringToInteger {
public static void main(String[] args) {
String s = "";
System.out.println(myAtoi(s));
}
private static int myAtoi(String s) {
s = s.trim();
if(s.length() == 0)
return 0;
int sign = 1;
long res=0;
int i = 0;
if(s.charAt(0) == '-') { sign = -1; i++;}
else if (s.charAt(0) == '+') { i++; }
while(i < s.length()) {
char ch = s.charAt(i);
if(ch >= '0' && ch <= '9') {
res = res * 10 + (ch - '0');
if(sign * res > Integer.MAX_VALUE) { return Integer.MAX_VALUE; }
else if (sign * res < Integer.MIN_VALUE) { return Integer.MIN_VALUE; }
i++;
} else
break;
}
return (int) ((int) sign * res);
}
}