码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-15 18:07:03      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

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 确认是否为数值

标签:

原文地址:http://www.cnblogs.com/Azhu/p/4226804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!