String to Integer II(lintcode 54)
Description
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
Interface
public class Solution {
/**
* @param str: A string
* @return An integer
*/
public int atoi(String str) {
// write your code here
}
}
Idea
The difficulty is a lot of conditions have to be considered.
Solution
public class Solution {
/**
* @param str: A string
* @return An integer
*/
public int atoi(String str) {
// write your code here
if (str == null || str.length() < 1) {
return 0;
}
str = str.trim();
char flag = '+';
int i = 0;
if (str.charAt(i) == '-') {
flag = '-';
++i;
} else if (str.charAt(i) == '+') {
++i;
}
double res = 0;
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
res = res * 10 + str.charAt(i) - '0';
++i;
}
if (flag == '-') {
res = -res;
}
if (res > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (res < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int)res;
}
}