String To Integer
String to integer, aka. atoi
, is a classic problem. The corresponding
problem is in fact a lot simple
as you actually do not need to consider power start from E
or e
. So the only problem
is to handle sign and number exceed. Integer that higher than Integer.MAX_VALUE
and
and lower than Integer.MIN_VALUE
will be cut off and just return the corresponding limit.
Here are two different solutions:
public class StringToInteger {
public int atoi(String str) {
char[] strchar = str.toCharArray();
int i = 0;
while (i < strchar.length && strchar[i] == ' ') i++;
long sign = 1;
long value = 0;
if (i >= strchar.length) return 0;
if (strchar[i] == '-') {
sign = -1;
i++;
}
else if (strchar[i] == '+') i++;
if (i < strchar.length && (strchar[i] < '0' || strchar[i] > '9')) return 0;
while (i < strchar.length && strchar[i] >= '0' && strchar[i] <= '9') {
value *= 10;
value += (long)(strchar[i] - '0');
i++;
if (value > 2147483647) break;
}
value = Math.abs(value) * sign;
if (value > 2147483647) return 2147483647;
if (value < -2147483648) return -2147483648;
return (int)value;
}
}
public class StringToInteger {
public int myAtoi(String string) {
long sign = 1;
long integer = 0;
int state = 0;
int i = 0;
char[] str = string.toCharArray();
while (i < str.length) {
char ch = str[i];
if (state == 0) {
// this is sign mode
if (ch == '-') {
sign = -1;
state = 1;
i++;
}
else if (ch == '+') {
state = 1; // switch to integer mode, so -+ and +- is not valid
i++; // skip plus sign or spaces in the head
}
else if (ch == ' ') i++;
else if (ch >= 0 && ch <= '9') state = 1; // switch to integer mode
else if (ch == '.') {
state = 2; // swich to decimal mode
i++;
} else break; // unexcepted char
} else if (state == 1) {
// this is integer mode
if (ch >= '0' && ch <= '9') {
integer = integer * 10 + (ch - '0');
if (integer > -(long)Integer.MIN_VALUE) break;
} else if (ch == '.') {
state = 2; // switch to decimal mode
} else if (ch == 'E' || ch == 'e') {
state = 3; // switch to power mode
} else break; // unexcepted char
i++;
}
}
long res = sign * integer;
if (res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
else if ( res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
return (int)res;
}
}