LeetCod 打卡13
字符串转整数 (atoi)
这次的题是刷题以来花费时间最长的。花了三个时间段。
最水的题,是目前碰到的,不过也带出了自身的一些问题。
首先,先看一下题目,其实刚开始看,发现很简单。做的时候也不难但是,却需要我们考虑多种情况。就是这些情况会让你焦头烂额,但是没通过的时候总觉得这就是最后一组情况了。所以我没放弃!
刚开始做的时候太轻敌,觉得正则不熟练,就用判断,于是一个晚上一个上午都没有解决了问题。
下面是错误的思路,大部分时间都浪费在这儿了。
public int myAtoi(String str) {
String res="";
String newStr= str.trim();
if(newStr.isEmpty()) {
return 0;
}
if((newStr.charAt(0)>57||newStr.charAt(0)<48)&&(newStr.charAt(0)!='-'&&newStr.charAt(0)!='+'))
return 0;
if(newStr.charAt(0)=='-'&&newStr.length()==1)
return 0;
if(newStr.length()>=2&&newStr.charAt(0)=='-') {
if(48<=newStr.charAt(1)&&newStr.charAt(1)<=57)
res="-";
else
return 0;
}
for(int i=0;i<newStr.length();i++) {
if(i>0&&(newStr.charAt(i)>57||newStr.charAt(i)<48))
break;
if(48<=newStr.charAt(i)&&newStr.charAt(i)<=57)
res=res+newStr.charAt(i);
}
if(res.isEmpty()) {
return 0;
}
if(res.charAt(0)=='-') {
res='-'+res.substring(1, res.length()).replaceAll("^(0+)", "");
}
res=res.replaceAll("^(0+)", "");
if(res.isEmpty()) {
return 0;
}
if(res.charAt(0)=='-')
if(res.length()>11)
return (int) -Math.pow(2, 31);
else if(res.length()==11&&res.compareTo("-2147483648")>0) {
return (int) -Math.pow(2, 31);
}
if(res.length()>10)
return (int)(Math.pow(2, 31)-1);
else if(res.length()==10&&res.compareTo("2147483647")>0)
return (int)(Math.pow(2, 31)-1);
if((res.charAt(0)=='-'||res.charAt(0)=='+')&&res.length()==1)
return 0;
long num=Long.parseLong(res);
if(num>(Math.pow(2, 31)-1))
return (int)(Math.pow(2, 31)-1);
if(num<-Math.pow(2, 31))
return (int) -Math.pow(2, 31);
return (int) num;
}
当改用正则表达式就简单多了,
public static int myAtoi(String str) {
if(str.trim().isEmpty())
return 0;
char flat=str.trim().charAt(0);
if((flat!='-'&&flat!='+')&&(flat>57||flat<48))
return 0;
if(str.trim().length()>1&&(flat=='-'||flat=='+')&&(str.trim().charAt(1)>57||str.trim().charAt(1)<48))
return 0;
String res="0";
String pattern = "-?[0-9]\\d*";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
while(m.find()) {
res=m.group(0);
break;
}
if(res.isEmpty())
return 0;
if(res.charAt(0)=='-') {
res='-'+res.substring(1, res.length()).replaceAll("^(0+)", "");
}
res=res.replaceAll("^(0+)", "");
if(res.isEmpty())
return 0;
if(res.charAt(0)=='-') {
if(res.length()>11)
return (int) -Math.pow(2, 31);
else if(res.length()==11&&res.compareTo("-2147483648")>0) {
return (int) -Math.pow(2, 31);
}
}
else if(res.length()>10)
return (int)(Math.pow(2, 31)-1);
else if(res.length()==10&&res.compareTo("2147483647")>0)
return (int)(Math.pow(2, 31)-1);
if((res.charAt(0)=='-'||res.charAt(0)=='+')&&res.length()==1)
return 0;
long num=Long.parseLong(res);
if(num>(Math.pow(2, 31)-1))
return (int)(Math.pow(2, 31)-1);
if(num<-Math.pow(2, 31))
return (int) -Math.pow(2, 31);
return (int) num;
}
下面是我的微信公众号,有问题可以一起聊一聊哦!