8. String to Integer (atoi)

My Solution (Flags)

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
public int myAtoi(String s) {
int length = s.length();
int sign = 1;
long result = 0;
boolean acceptSpace = true;
boolean acceptSign = true;
boolean acceptZero = true;
for (int i = 0; i < length; i++) {
// get char
char currentChar = s.charAt(i);
// process whitespace
if (currentChar == ' ' && acceptSpace) {
continue;
} else if (currentChar == ' ' && !acceptSpace) {
break;
}
// process sign
else if (currentChar == '+' && acceptSign) {
acceptSpace = false;
acceptSign = false;
continue;
}

else if (currentChar == '-' && acceptSign) {
acceptSpace = false;
acceptSign = false;
sign = -1;
continue;
}

else if (currentChar == '0' && acceptZero) {
acceptSpace = false;
acceptSign = false;
continue;
}

else if (Character.isDigit(currentChar)) {
acceptSpace = false;
acceptSign = false;
acceptZero = false;

int digit = currentChar - '0';
if (result > Integer.MAX_VALUE / 10 ||
(result == Integer.MAX_VALUE / 10 && digit > (sign == 1 ? 7 : 8))) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}

result = result * 10 + digit;
}

else {
break;
}
}

result = result * sign;
if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
return (int) result;

}
}

Remarks:

  1. Check the last digit of MAX value of int boundary: result == Integer.MAX_VALUE / 10 && digit > (sign == 1 ? 7 : 8))

  2. Use long to store the intermediate result, and check if the result is out of bound at last:

    1
    2
    3
    if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
    if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
    return (int) result;

While Loops

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
public class Solution {
public int myAtoi(String s) {
int i = 0, n = s.length();
int sign = 1;
int result = 0;

// Step 1: Skip leading whitespaces
while (i < n && s.charAt(i) == ' ') {
i++;
}

// Step 2: Check sign
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
sign = s.charAt(i) == '-' ? -1 : 1;
i++;
}

// Step 3: Read digits
while (i < n && Character.isDigit(s.charAt(i))) {
int digit = s.charAt(i) - '0';

// Step 4: Handle overflow
if (result > (Integer.MAX_VALUE - digit) / 10) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}

result = result * 10 + digit;
i++;
}

return result * sign;
}
}

Remarks:

  1. result * 10 + digit > Integer.MAX_VALUE -> result > (Integer.MAX_VALUE - digit) / 10 Use this to check out of bound