小声BB几句:好久没有动手写博客了,因为觉得自己一直在给搜索引擎制造垃圾(相似的内容,前辈们都写过啦)。后来还是想通了,当成是自己的线上笔记吧。
问题:
实现一个方法,输入为一个字符串,输出为字符串转成的double类型的数字。如果字符串中存在非法字符,抛出异常。
分析:
这个问题是饿了么的面试官问我的,主要是想考查如何思考对于输入的字符串合法。对于这个问题,面试官引导我先写几个测试用例,找出合法字符串的特征,我们可以考虑以下用例:
“123.670”——合法
“-123.689”——合法
“da12.3”——不合法
“12”——合法
“12.3.9”——不合法
“00.123”——不合法
我们可以从四个方面考虑:
- 能出现的字符:负号(-),数字(0-9),小数点(.)
- 出现的次数:负号(-),小数点(.)一次,大小是否越界(越界这个我不会,(⊙o⊙)…)
- 出现的位置:负号(-)必须在最前,而(.)必须在中间(最前或者最后都不行)
- 出现的组合:001,002这种(这点我理解为,0出现的位置,如果第一个字符是0,而他后面没有紧接着出现小数点那么这就是一个不合法的字符串)
public static double stringToDouble(String str) throws Exception{
boolean negative = false;
double sum = 0.0d;
boolean pointAppear = false;
int count = 1;//用来记录小数点后几位
if(str == null || str.equals("")){
throw new Exception("重新输入字符串");
}
for(int i=0;i<str.length();i++){
//判断第一个字符是不是负号
if(i == 0 && (str.charAt(0)=='-'||str.charAt(0)=='+')){
if(str.charAt(i) == '-')
negative = true;
}else{
//判断是否为小数点
if(pointAppear == false && i !=0 && str.charAt(i) == '.'){
pointAppear = true;
}else if(str.charAt(i)>='0' && str.charAt(i)<='9'){
if(i==0 && str.charAt(i) == '0' ){
if(str.charAt(i+1) != '.')
throw new Exception("不合法字符串1");
}
if(i==1 && str.charAt(i) == '0' && (str.charAt(0)=='-'||str.charAt(0)=='+')){
if(str.charAt(i+1) != '.')
throw new Exception("不合法字符串2");
}
//整数部分
if(pointAppear == false){
sum = sum*10 +(str.charAt(i)-'0');
if(sum > Double.MAX_VALUE) {
throw new Exception("越界");
}
}else{
sum = sum + Math.pow(0.1,count)*(str.charAt(i)-'0');
count++;
}
}else{
throw new Exception("不合法字符串3");
}
}
}
return negative == true ? sum*(-1):sum;
}