依次判断:
数字的格式可以用A[.[B]][e|EC]或者.B[e|EC]表示,
其中A和C都是整数(可以有正负号,也可以没有),而B是一个无符号整数
c++
class Solution {
public:
// 数字的格式可以用A[.[B]][e|EC]或者.B[e|EC]表示,
// 其中A和C都是整数(可以有正负号,也可以没有),而B是一个无符号整数
bool isNumber(string s) {
if(s.size() == 0)
return false;
int index = 0;
while(s[index] == ' '){ // 越过空格
index++;
}
bool numeric = scanInteger(s, index); // 越过+-号和数字;
// 如果出现'.',
if(s[index] == '.'){ // 越过.号
index++;
// .123 233. 233.666 均合法
// 必须先判断scanUnsignedInteger, 否则 numeric true则不执行scanUnsignedInteger(s, index),那么index无法越过小数点后数字,scanUnsignedInteger函数越过数字
numeric = scanUnsignedInteger(s, index) || numeric ;
// true,false 有数字,无数字 +233.
// true,true: 有数字,有数字 +233.666
// false,true: 无数字,有数字 .123
}
// 如果出现'e'或者'E',接下来跟着的是数字的指数部分
if(s[index] == 'e' || s[index] == 'E'){
index++;
// 不合法: 当e或E前面没有数字时,.e1、e1
// 不合法: 当e或E后面没有整数时,12e、12e+5.4
numeric = numeric && scanInteger(s ,index); // 越过+-号和数字
}
while(s[index] == ' '){ // 越过结尾空格
index++;
}
return numeric && index == s.size();
}
private: // 判断是否是+123
// 越过+-号
bool scanInteger(string s, int& index){
if(s[index]=='+' || s[index]=='-'){
index++;
}
return scanUnsignedInteger(s, index); // index指针已经指向.后一位
}
// 越过数字
bool scanUnsignedInteger(string s, int& index){
int befor = index;
while(index != s.size() && s[index] >= '0' && s[index] <= '9'){
index++;
} // 跳出循环时 越过数字or字符串结束
return index > befor; // 有数字
}
};