65有效数字(面向测试用例编程)

1、题目描述

验证给定的字符串是否可以解释为十进制数字。

2、示例

true:".1"、"-.1"、"1."、" 005"

false:"."、"+e"、"+3. e04116"、" 99e2.5 "

说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。这里给出一份可能存在于有效十进制数字中的字符列表:数字 0-9 指数 "e" 正/负号 "+"/"-" 小数点 "."
当然,在输入中,这些字符的上下文也很重要。

3、题解

基本思想:面向测试用例编程。易错用例:true:".1"、"-.1"、"1."、" 005";false:"."、"+e"、"+3. e04116"。

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
	bool isNumber(string s) {
		//基本思想:面向测试用例编程。易错用例:true:".1"、"-.1"、"1."、" 005";false:"."、"+e"、"+3. e04116"
		int i, flag = 0;
		//去除开头空格
		remove_space(s, 0);
		if (s.empty())
			return false;
		//去除开头+-号
		remove_sighed(s, 0);
		if (s.empty())
			return false;
		//s必须以.或1-9开头
		if ((s[0] >= '0' && s[0] <= '9') || s[0]=='.')
		{
			i = 0;
			while (i < s.size() && s[i] >= '0' && s[i] <= '9')
			{
				i++;
				flag = 1;
			}
			//s为整数
			if (i == s.size())
				return true;
			if (s[i] == ' ')
			{
				remove_space(s, i);
				if (i == s.size())
					return true;
				else
					return false;
			}
			//s为整数科学计数
			if (s[i] == 'e')
				return check_e(s, i);
			//s为浮点数
			if (s[i] == '.')
			{
				i++;
				//s为浮点数1.情况
				if (i < s.size() && s[i] == ' ')
				{
					remove_space(s, i);
					if (i == s.size() && flag==1)
						return true;
					else
						return false;
				}
				//s为浮点数1.1情况
				while (i < s.size() && s[i] >= '0' && s[i] <= '9')
				{
					i++;
					flag = 1;
				}
				if (flag == 0)
					return false;
				remove_space(s, i);
				if (i == s.size())
					return true;
				//s为浮点数科学计数1.1e2情况
				if (s[i] == 'e')
					return check_e(s, i);
				else
					return false;
			}
			return false;
		}
		return false;
	}
	//用于去除+-号
	void remove_sighed(string& s, int i)
	{
		if (i < s.size() && (s[i] == '+' || s[i] == '-'))
			s.erase(i, 1);
	}
	//用于去除开头和结尾连续空格
	void remove_space(string& s,int i)
	{
		int start = i;
		while (i < s.size() && s[i] == ' ')
			i++;
		s.erase(start, i - start);
	}
	//如果是科学计数,检查是否满足科学计数法
	bool check_e(string& s, int i)
	{
		if (i == s.size() - 1)
			return false;
		i++;
		remove_sighed(s, i);
		remove_space(s, i);
		if (i == s.size())
			return false;
		if (s[i] < '0' || s[i] > '9')
			return false;
		while (i < s.size() && s[i] >= '0' && s[i] <= '9')
			i++;
		remove_space(s, i);
		if (i == s.size())
			return true;
		else
			return false;
	}
};
int main()
{
	Solution solute;
	string s = "+3. e04116";
	cout << solute.isNumber(s) << endl;
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值