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.

分析

这种故意把题目写得模糊的题目,一般都会被选手们标记为dislike。我也不是很喜欢这种题。不过这题感觉并不难,就是有点烦而已。判断的条件罗列如下:

  • 开头和结尾可以是空格,其余位置不允许出现空格
  • 空格除外的部分,开头可以有一个正负号
  • 剩下的部分,只能是数字、'e'、正负号或者小数点,且除数字外,都只能出现一次
  • 这部分中,只能以小数点和数字开头
  • 正负号只能出现在'e'的后面
  • e的后面必须接整数,可以带正负号
  • e的前面必须有数字,可以是整数或这小数,小数可以省略小数点前或者后面的零(但不能都省略)

实现

class Solution {
public:
    bool isNumber(string s) {
        bool exp=false, point=false, num=false;
        int i=0, start, end, epos, ppos;
        while(i'9')
                return false;
            else{
                num = true;
            }
            i++;
        }
        end = i-1;
        if(exp && (
            (start == epos || end == epos) || (epos+1

思考

这题我是边改边提交边看数据来做的,这样的做法不值得推荐。希望以后能够一次通过吧。

你可能感兴趣的:(65. Valid Number)