leetcode-表示数值的字符串

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

例如:
“0” => true
" 0.1 " => true
“abc” => false
“1 a” => false
“2e10” => true
" -90e3 " => true
" 1e" => false
“e3” => false
" 6e-1" => true
" 99e2.5 " => false
“53.5e93” => true
" --6 " => false
“-+3” => false
“95a54e53” => false

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

当然,在输入中,这些字符的上下文也很重要。

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;


class Solution {
public:
	bool isInt(string& s, int& index) {		// 判断是不是带有正负号的整数
		if (index < s.size() && (s[index] == '-' || s[index] == '+')) index++;
		return isUnsigned(s, index);
	}

	bool isUnsigned(string& s, int& index) { // 判断无符号整数
		int pre = index;
		while (index < s.size()) {
			if (s[index] >= '0' && s[index] <= '9') index++;
			else break;
		}
		return index > pre;
	}

    bool isNumber(string s) {
    	if (s.empty()) return false;
    	int index = 0;
    	while (index < s.size() && s[index] == ' ') index++; // 去掉前面的空格
        bool ans = isInt(s, index);
        if (index < s.size() && s[index] == '.') {
        	index++;
        	ans = isUnsigned(s, index) || ans; // 如果有小数点,只有前后都没有数字才不对
        }
        if (index < s.size() && s[index] == 'e') {
        	index++;
        	ans = isInt(s, index) && ans;  // 如果出现指数e,则e的前后都必须要有整数
        }
        while (index < s.size() && s[index] == ' ') index++; // 去掉后面的空格
        return ans && index == s.size();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yhwang-hub

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值