总结得知,我们需要对应是否为数字、小数、符号、指数设置 4 个 flag,然后依次迭代字符串的每一个字符,根据当前 flag 的值进行判断。
/** * @param {string}s * @return {boolean} */ var isNumber = function (s) { let num, dec, sign, exp; for (let c of s.split("")) { // Check number. if (c >= "0" && c <= "9") num = true; // Check sign. elseif (c === "+" || c === "-") { // If sign duplicated or appears after number or decimal. if (sign || num || dec) returnfalse; sign = true; // Check decimal. } elseif (c === ".") { // If duplicated or appears after exponent. if (dec || exp) returnfalse; dec = true; // Check exponent. } elseif (c === "e" || c === "E") { // If duplicated or no number before it. if (exp || !num)) returnfalse; (exp = true), (num = false), (sign = false), (dec = false); // Failed. } else { returnfalse; } } return !!num; };