Interview Question 20. A string representing a numeric value
This example is disgusting
Only spaces-false
Only a decimal point-false (use bool num to determine whether a number appears)
Can be a space at the end
The decimal point can be at the 1st place and the decimal point can be at the end. . .
This question has been submitted more than a dozen times, because of the boundary conditions of these spicy chickens
class Solution {
public:
bool isNumber(string s) {
if(s.empty()) return false;
int e=-1;
while(s[0]==' '){
s.erase(0,1);
}
while(1){
int j=s.size()-1;
if(j>=0&&s[j]==' '){
s.erase(j,1);
}
else break;
}
if(s.empty()) return false;
bool point=false;
bool num=false;
int n=s.size();
for(int i=0;i<n;i++){
if(s[i]=='+'||s[i]=='-'){
if(i!=e+1) return false;
}
else if(s[i]=='.'){
if(point || e!=-1 ) return false;
point=true;
}
else if(s[i]=='e'){
if(!num || e!=-1) return false;
num=false;
e=i;
}
else if(s[i]<'0' || s[i]>'9') return false;
else num=true;
}
return num;
}
};