shinena / myProject

1 stars 0 forks source link

Javascript 表示数值的字符串 #38

Open shinena opened 5 years ago

shinena commented 5 years ago

题目描述: 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。

思路: 首先判断是否有符号(+或者-),如果有,则对后面的字符串判断 首先需要扫描数字直到结束或是遇到其他字符,结束则返回true,否则继续按情况判断下一个需要判断的字符

如果是小数点'.',是则扫描数字,直到结束(返回true)或者遇到特殊字符,如果是e或E,那么对后面的数判断是否符合指数表示,如果是其他字符则返回false。 如果是e或者E,那么对后面的数判断是否符合指数表示。 如果不符合上面的情况则返回false 指数判断: 首先判断是否是符号,如果是,跳到下一位判断后面的是否是数字组成的串,是则表示指数表示是正确的,否则是不正确的。

function isNumberic(str) {
  if(str == null || str.length == 0) return false;
  //首先如果两边有空格的话需要先去掉空格
  let index = 0;
  let length = str.length;
  while(index < length && str[index] == ' ') index++;
  if(index >= length) return false;
  while(str[length - 1] == ' ') length--;
  //第一步:判断是否是一个整数
  //如果第一位是+或者-号的时候
  if(str[index] == '+' || str[index] == '-') index++;
  if(index >= length) return false;
  //如果后面是数字的话就跳过
  while(index < length && str[index] >= '0' && str[index] <= '9') index++;
  if(index == length) return true;
  let index2 = index;
  //第二步:判断是否还有小数部分
  if(str[index] == '.'){
      index++;
      if(index == length) return true;
      index2 = index;
      while(index < length && str[index] >= '0' && str[index] <= '9') index++;
      if(index == index2) return false;
      if(index == length) return true;
  }

  //第三步:判断是否有科学计数法
  if(str[index] == 'e' || str[index] == 'E'){
      index++;
      if(index == length) return false;
      if(str[index] == '+' || str[index] == '-') index++;
      index2 = index;
      while(index < length && str[index] >= '0' && str[index] <= '9') index++;
      if(index == index2) return false;
      if(index == length) return true;
  }
  return false;
}
shinena commented 5 years ago

使用正则表达式进行匹配

function isNumberic(str){
  if(str == null || str.length == 0){
    return
  }
  return str.match("[\\+-]?[0-9]*(\\.[0-9]*)?([eE][\\+-]?[0-9]+)?")
}