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 @   aiterator  阅读(157)  评论(0编辑  收藏  举报
编辑推荐:
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!
点击右上角即可分享
微信分享提示