-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstringToInteger.java
32 lines (26 loc) · 1017 Bytes
/
stringToInteger.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
class Solution {
public int myAtoi(String s) {
int index = 0, sign = 1, total = 0;
int n = s.length();
// Step 1: Ignore leading whitespaces
while (index < n && s.charAt(index) == ' ') {
index++;
}
// Step 2: Check for '+' or '-'
if (index < n && (s.charAt(index) == '+' || s.charAt(index) == '-')) {
sign = (s.charAt(index++) == '-') ? -1 : 1;
}
// Step 3: Read digits until a non-digit character is encountered
while (index < n && Character.isDigit(s.charAt(index))) {
int digit = s.charAt(index++) - '0';
// Step 4: Check for overflow
if (total > Integer.MAX_VALUE / 10 || (total == Integer.MAX_VALUE / 10 && digit > 7)) {
return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
// Update total
total = total * 10 + digit;
}
// Apply sign to the result
return total * sign;
}
}