题解 | #表示数值的字符串#
表示数值的字符串
https://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return bool布尔型 */ function isNumeric( str ) { // write code here // 去掉字符串两端的空格 str = str.trim(); // 如果字符串为空,则不是数值 if (str === "") { return false; } // 判断是否有符号(+/-) let index = 0; if (str[index] === '+' || str[index] === '-') { index++; } // 判断是否有整数部分 let hasIntegerPart = false; while (index < str.length && /\d/.test(str[index])) { index++; hasIntegerPart = true; } // 判断是否有小数点 if (str[index] === '.') { index++; } // 判断是否有小数部分(可以为空) let hasDecimalPart = false; while (index < str.length && /\d/.test(str[index])) { index++; hasDecimalPart = true; } // 判断是否有科学计数法部分 if (str[index] === 'e' || str[index] === 'E') { index++; if (str[index] === '+' || str[index] === '-') { index++; } let hasExponentPart = false; while (index < str.length && /\d/.test(str[index])) { index++; hasExponentPart = true; } // 如果没有科学计数法部分,则不是数值 if (!hasExponentPart) { return false; } } // 检查是否已经处理完整个字符串 return index === str.length && (hasIntegerPart || hasDecimalPart); } module.exports = { isNumeric : isNumeric };