1.myAtoi()使用正则表达式 不完善
2.myAtoi2()完善
public int myAtoi(String s) {
int res = 0;
String[] split = s.split("");
int x = 0;
String str = "";
int z = 1;// 记录符号 默认为正
String regex = "\\s+";// 正则表达式过滤空格
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
// 去除空格
x = matcher.end();
}
if (split[x].matches("\\-")) {
z = -1;
x += 1;
}
if (split[x].matches("\\+")) {
z = 1;
x += 1;
}
// 开头或者符号后面跟着不是1-9 直接返回0
if (!split[x].matches("[1-9]")) {
res = 0;
} else {
while (x < split.length) {
if (split[x].matches("\\d")) {
str += split[x];
x += 1;
} else {
break;
}
}
res = z * Integer.parseInt(str);
}
return res;
}
public int myAtoi2(String s) {
int res = 0;
if (s.length() != 0) {
char[] charArray = s.toCharArray();
int x = 0;
// 记录下标
String str = new String("");
int z = 1;
// 记录符号 默认为正
// 去除空格
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] != ' ') {
x = i;
break;
}
}
// 记录符号
if (charArray[x] == '-') {
z = -1;
x += 1;
} else if (charArray[x] == '+') {
z = 1;
x += 1;
}
// 开头或者符号后面跟着不是1-9 直接返回0
if (x >= charArray.length || !Character.isDigit(charArray[x])) {
res = 0;
} else {
while (x < charArray.length) {
if (charArray[x] == '0') {
x += 1;
} else {
break;
}
}
while (x < charArray.length) {
if (Character.isDigit(charArray[x])) {
str += charArray[x];
x += 1;
} else {
break;
}
}
if (!str.equals("") && str.length() <= 10) {
long d = Long.parseLong(str);
if (z == -1 && -d < Integer.MIN_VALUE) {
res = Integer.MIN_VALUE;
} else if (z == 1 && d > Integer.MAX_VALUE) {
res = Integer.MAX_VALUE;
} else {
res = (int) (d * z);
}
}
if (str.length() > 10 && z == -1) {
res = Integer.MIN_VALUE;
}
if (str.length() > 10 && z == 1) {
res = Integer.MAX_VALUE;
}
}
} else {
res = 0;
}
return res;
}
p.s.欢迎指正