博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Valid Number leetcode
阅读量:6906 次
发布时间:2019-06-27

本文共 1487 字,大约阅读时间需要 4 分钟。

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.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

这道题之所以是hard难度,是因为它隐含的输入种类非常之多,要想将所有的情况考虑完全,并且找出这些情况之间的逻辑关系,用尽可能少的代码实现出来,而不冗余,难度非常之大。

还好题目中给出了5种可能的输入情况,减少了我们试错的次数。

总结一下情况:

1.可以有+-号(如果有e,前后的数需要分别判断,这里没有"+-"和"-+"的坑爹情况)

2.可以有小数点(但只能有一个)

3.不能有字母(e除外)

4.必须有数字(如果有e,e的前面数和后面的数需要分别判断)

5.可以有空格,但必须出现在字符串的前面和后面(像这种 "-   1"、"1   e   1"都是不被允许的)

这些情况都是无数的先辈被折磨到口吐鲜血才总结出来的。

我是个懒人,也不是自虐狂,所以就直接拿来主义了。

不过程序是自己实现了

bool isNumber(string s) {    int i = 0;    while (s[i] == ' ')        i++;    if (s[i] == '+' || s[i] == '-')        i++;    int n_point = 0, n_num = 0;    while (isdigit(s[i]) || s[i] == '.')        s[i++] == '.' ? n_point++ : n_num++;    if (n_point > 1 || n_num < 1)        return false;    if (s[i] == 'e') {        i++;        if (s[i] == '+' || s[i] == '-')            i++;        int n_num = 0;        while (isdigit(s[i]))        {            i++;            n_num++;        }        if (n_num < 1)            return false;    }    while (s[i] == ' ')        i++;    return i == s.length();}

总结:

想好了再编程,清楚了需求再编程,别手犯贱!

转载于:https://www.cnblogs.com/sdlwlxf/p/5116254.html

你可能感兴趣的文章
VMware中通过克隆的Centos7,网卡突然没了
查看>>
学习笔记 DNS 子域授权 view
查看>>
stat函数
查看>>
在MyEclipse中部署项目到Tomcat服务器
查看>>
Kendo UI常用示例汇总(二十二)
查看>>
lnmp+coreseek实现站内全文检索(安装篇)
查看>>
六月技术指标和个人指标
查看>>
我的友情链接
查看>>
dojo layout
查看>>
初探 ELK - 每天5分钟玩转 Docker 容器技术(89)
查看>>
c#通过创建Windows服务启动程序
查看>>
系统架构设计指南
查看>>
我的友情链接
查看>>
Jquery Ajax方法传值到action
查看>>
亚马逊图书推荐--我感兴趣的
查看>>
Xmanager连接Centos6.3的远程桌面
查看>>
Office365:客户端升级后无法启动Microsoft Outlook
查看>>
我的友情链接
查看>>
在eclipse中查看Android源代码
查看>>
prometheus+grafana
查看>>