首页 > 代码库 > [LeetCode] Valid Number 确认是否为数值

[LeetCode] 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.

click to show spoilers.

Update (2014-12-06):
New test cases had been added. Thanks unfounder‘s contribution.


  确认输入的字符串是否为一个数值,一系列的判断,主要是一些位置的判断:
  1. 输入前置空格
  2. 正负号
  3. 连续的数值,包括‘.’
  4. 符号e
  5. 正负号
  6. 连续数值,不包括‘.‘
  7. 后续空格

按上面的规则便行。

#include <iostream>using namespace std;class Solution {public:    bool isNumber(const char *s)    {        int idx =0;        for(;s[idx]== ;idx++);        if(s[idx]==-||s[idx]==+)    idx++;        int Point=0,Num=0;        for(;(s[idx]>=0&&s[idx]<=9)||s[idx]==.;idx++)            s[idx]==.?Point++:Num++;        if(Point>1||Num<1)  return false;        if(s[idx]==e){            idx++;            if(s[idx]==-||s[idx]==+)    idx++;            Num=0;            for(;s[idx]>=0&&s[idx]<=9;idx++)    Num++;            if(Num<1)   return false;        }        for(;s[idx]== ;idx++);        return s[idx]==\0;    }};int main(){    char a[]="-e-";    Solution sol;    cout<<sol.isNumber(a)<<endl;    return 0;}

 

[LeetCode] Valid Number 确认是否为数值