-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringToIntegerAtoi.java
39 lines (33 loc) · 1.19 KB
/
StringToIntegerAtoi.java
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
package String;
class StringToIntegerAtoi {
public static void main(String[] args) {
int res = myAtoi("jatin 0345");
System.out.println(res);
}
public static int myAtoi(String str) {
int index = 0, sign = 1;
if(str.length() == 0) return 0;
while(index < str.length() && str.charAt(index) == ' ')
index++;
if(index < str.length() && (str.charAt(index) == '+' || str.charAt(index) == '-')) {
sign = str.charAt(index) == '+' ? 1 : -1;
index++;
}
if(index < str.length() && !Character.isDigit(str.charAt(index))) return 0;
int result = 0;
while(index < str.length()) {
if(!Character.isDigit(str.charAt(index))) break;
char current = str.charAt(index++);
int previous = result;
result *= 10;
if(previous != result/10) {
return sign == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
result += (current - '0');
if(result < 0) {
return sign == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
}
return result * sign;
}
}