-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplement atoi
49 lines (39 loc) · 1.18 KB
/
Implement atoi
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
40
41
42
43
44
45
46
47
48
49
//Implement atoi
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine();
while(t > 0) {
String str = sc.nextLine();
Solution obj = new Solution();
int num = obj.myAtoi(str);
System.out.println(num);
System.out.println("~");
t--;
}
}
}
class Solution {
public int myAtoi(String s) {
int INT_MAX = 2147483647, INT_MIN = -2147483648;
int i = 0, n = s.length(), sign = 1, result = 0;
while(i < n && s.charAt(i) == ' ') {
i++;
}
if(i < n && (s.charAt(i) == '-' || s.charAt(i) == '+')) {
sign = s.charAt(i) == '-' ? -1 : 1;
i++;
}
while(i < n && Character.isDigit(s.charAt(i))) {
int digit = s.charAt(i) - '0';
if(result > (INT_MAX - digit) / 10) {
return sign == 1 ? INT_MAX : INT_MIN;
}
result = result * 10 + digit;
i++;
}
return sign * result;
}
}