LeetCode 65 Valid Number

 (在队友怂恿下写了LeetCode上的一个水题)

传送门

题意

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.


Solution

题意是判断一个串是不是合法的实数(double literal),实际上是想让你实现 istream::istream &operator>>(const double &)(针对C++而言)。

我们当然可以 hand-code 出这个函数,但是更好的做法的利用 istream 类的某些 flag(member function)以其人之道还治其人之身。

Implementation

复制代码
 1 class Solution {
 2 public:
 3     bool isNumber(string s) {
 4         int b=0, e=s.size();
 5         for(; isspace(s[b]); b++);
 6         for(; isspace(s[e-1]); e--);
 7         string t=s.substr(b, e-b);
 8         if(*t.rbegin()!='.'&&!isdigit(*t.rbegin())) return false;
 9         if(*t.rbegin()=='.'&&!isdigit(*(t.rbegin()+1))) return false; 
10         stringstream x(t);
11         double y;
12         x>>y;
13         return x.eof();
14     }
15 };
复制代码

这大概是目前为止最短的C++实现了(如果不用regular expression的话)。。。(逃)

如果C++中double的范围充分大,还可以实现得更短:

复制代码
 1 class Solution {
 2 public:
 3     bool isNumber(string s) {
 4         int b=0, e=s.size();
 5         for(; isspace(s[b]); b++);
 6         for(; isspace(s[e-1]); e--);
 7         stringstream x(s.substr(b, e-b));
 8         double y;
 9         x>>y;
10         return !x.fail() && x.eof();
11     }
12 };
复制代码

 

posted @   Pat  阅读(236)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
点击右上角即可分享
微信分享提示