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

大意就是给你一个字符串判断是否是一个数字。

** 注意**一下三种情况:

  • +1234
  • +123.56
  • +123.48e-10

代码写的太恶心了。wa了好多次!

class Solution {
	bool judgeNumber(string &str, int b, int e)
	{
		bool is = false, res = false;
		for(int i=b; i<e; ++ i)
		{
			if(i == 0 && (str[i] == '-' || str[i] == '+'))
				continue;

			if(str[i] >= '0' && str[i] <= '9')
			{
				res = true;
				continue;
			}

			if(str[i] == '.' && is == false)
				is = true;
			else
				return false;
		}
		return res;
	}

public:
    bool isNumber(string s) {
    	
    	int e = -1;
    	string str;
    	for(int i=0; ;)
    	{
    		while(i < s.size() && s[i] == ' ')
    			i ++;
    		if(i >= s.size())
    			return false;
    		while(i < s.size() && s[i] != ' ')
    		{
    			if(s[i] == 'e')
    				e = str.size();
    			str += s[i ++];
    		}
    		while(i < s.size() && s[i] == ' ')
    			i ++;
    		if(i < s.size())
    			return false;
    		break;
    	}

    	//1. +1234
    	//2. -12345.45
    	//3. +12345.45e+10

    	if(e == -1)
    		return judgeNumber(str, 0, str.size());

    	bool is = judgeNumber(str, 0, e);
    	if(is == false)
    		return false;

    	is = false;
    	for(int i=e+1; i<str.size(); ++ i)
    	{
    		if(i == e+1 && (str[i] == '-' || str[i] == '+'))
    			continue;

    		if(str[i] >= '0' && str[i] <= '9')
    		{
    			is = true;
    			continue;
			}

    		return false;
    	}
    	return is;
    }
};
posted @ 2017-04-11 20:42  aiterator  阅读(157)  评论(0编辑  收藏  举报