String to Integer(atoi)

Implement function atoi to convert a string to an integer.

If no valid conversion could be performed, a zero value is returned.

If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Example
"10" => 10

"-1" => -1

"123123123123123" => 2147483647

"1.0" => 1

Leetcode
Lintcode

Solution:

Detailed problem.
Three derails should be noted:

1. valid char c : c - '0',
2. not valid char: stop
3. '+' or '-' sign at the start, record it
4. Overflow: INT_MAX (2147483647) or INT_MIN (-2147483648) is returned
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
public class Solution {
public int atoi(String str) {
// write your code here
if (str == null || str.length() == 0)
return 0;
int sign = 1;
int index = 0;

// if we use long, we should return MAX or MIN value directly,
double num = 0;


str = str.trim();

if (str.charAt(index) == '+')
index++;
else if (str.charAt(index) == '-'){
sign = -1;
index++;
}

for (; index < str.length(); index++){
char current = str.charAt(index);
if (current > '9' || current < '0' || num > Integer.MAX_VALUE)
break;
num = num * 10 + (current - '0');
}

return (int) (sign * num);
}


// If double and long are not allowed
public int atoi(String str) {
// write your code here
if (str == null || str.length() == 0)
return 0;
int sign = 1;
int index = 0;
int num = 0;

str = str.trim();

if (str.charAt(index) == '+')
index++;
else if (str.charAt(index) == '-'){
sign = -1;
index++;
}

for (; index < str.length(); index++){
char current = str.charAt(index);
if (current > '9' || current < '0')
break;
if (num > Integer.MAX_VALUE / 10
|| (num == Integer.MAX_VALUE / 10 && num > Integer.MAX_VALUE % 10))
return sign > 0? Integer.MAX_VALUE : Integer.MIN_VALUE;
num = num * 10 + (current - '0');
}

return (int) (sign * num);
}
}