# String to Integer

## Question

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


## 题解

### Java

public class Solution {
/**
* @param str: A string
* @return An integer
*/
public int atoi(String str) {
if (str == null || str.length() == 0) return 0;

// trim left and right spaces
String strTrim = str.trim();
int len = strTrim.length();
// sign symbol for positive and negative
int sign = 1;
// index for iteration
int i = 0;
if (strTrim.charAt(i) == '+') {
i++;
} else if (strTrim.charAt(i) == '-') {
sign = -1;
i++;
}

// store the result as long to avoid overflow
long result = 0;
while (i < len) {
if (strTrim.charAt(i) < '0' || strTrim.charAt(i) > '9') {
break;
}
result = 10 * result + sign * (strTrim.charAt(i) - '0');
// overflow
if (result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
i++;
}

return (int)result;
}
}