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.
这道题要求判断给出的字符串是否是有效的数字。先删除字符串两边的空格符,然后直接用strtod转换成双精度浮点型,最后如果剩余的字符串长度超过0的话说明不是有效的数字。这样的做法也能通过,但感觉上是不完美的,因为不能判断超过double的范围的数。
代码:
class Solution
{
public:
bool isNumber(string s)
{
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
if(s.empty()) return false;
char *end;
double d=strtod(s.c_str(),&end);
if(strlen(end)>0) return false;
else return true;
}
};