把字符串转换成整数-67
请你写一个函数StrToInt,实现把字符串转换成整数这个功能。
当然,不能使用atoi或者其他类似的库函数。
样例
输入:"123"
输出:123
注意:
你的函数应满足下列条件:
- 忽略所有行首空格,找到第一个非空格字符,可以是 ‘+/−’ 表示是正数或者负数,紧随其后找到最长的一串连续数字,将其解析成一个整数;
- 整数后可能有任意非数字字符,请将其忽略;
- 如果整数长度为0,则返回0;
- 如果整数大于INT_MAX(2^31 − 1),请返回INT_MAX;如果整数小于INT_MIN(−2^31) ,请返回INT_MIN;
思路:
先将字符串去除首尾空格,然后判断第一位是否合法。
遍历过程中判断下一次是否会溢出,判断方法参考整数反转。
class Solution {
public int myAtoi(String str) {
if (str == null || str.length() == 0) return 0;
str = str.trim();
if (str.equals("")) return 0;
int i = 0, res = 0, n = str.length();
boolean negetive = false;
if (str.charAt(i) == '+' || str.charAt(i) == '-') {
if (str.charAt(i) == '-') negetive = true;
i++;
}
while (i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
int temp = str.charAt(i) - '0';
if (negetive) temp = -temp;
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10
&& temp > 7))
return Integer.MAX_VALUE;
if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10)
&& temp < -8)
return Integer.MIN_VALUE;
res = res * 10 + temp;
i++;
}
return res;
}
}
有特殊字符时就算无效的字符串
public class Solution {
static boolean isValid = false;
public int StrToInt(String str) {
if (str == null || str.length() <= 0) return 0;
char[] chars = str.toCharArray();
long num = 0;
boolean minus = false;
for (int i = 0; i < chars.length; i++) {
if (i == 0 && chars[i] == '-')
minus = true;
else if (i == 0 && chars[i] == '+')
minus = false;
else {
int a = (int) (chars[i] - '0');
if (a > 9 || a < 0) {
isValid = false;
return 0;
}
num = !minus ? num * 10 + a : num * 10 - a;
if ((!minus && num > Integer.MAX_VALUE) || (minus && num < Integer.MIN_VALUE)) {
isValid = false;
return 0;
}
}
}
return (int) num;
}
}