65. Valid Number
题目
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
解析
//链接:https://www.nowcoder.com/questionTerminal/608d810765a34df2a0d47645626dd2d3
class Solution {
public:
bool isNumber(const char *s)
{
string str(s);
int index = str.find_first_not_of(' ');
if (str[index] == '+' || str[index] == '-') //正负号
index++;
int points = 0, numbers = 0;
for (; str[index] >= '0' && str[index] <= '9' || str[index] == '.'; index++)
s[index] == '.' ? ++points : ++numbers;
if (points > 1 || numbers < 1)
return false;
if (str[index] == 'e' || str[index] == 'E')
{
index++;
if (str[index] == '+' || str[index] == '-') // E后面也有正负号
index++;
int afterE = 0;
for (; str[index] >= '0' && str[index] <= '9'; index++)
afterE++;
if (afterE < 1)
return false;
}
for (; str[index] == ' '; index++){}
return str[index] == ' ';
}
};
题目来源