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

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

I guess some of you may have noticed that this seemingly simple problem has the lowest acceptance rate among all problems on the LeetCode OJ. Well, some of you may also complain about the annoying large number of special cases and have no idea of how to handle them systematically. Well, provides a nicely systematic idea, which gives a very clean and clear code. Take a look at it and you will become happy with this problem :-)

The code is rewritten as follows.

1 class Solution { 2 public: 3     bool isNumber(string s) { 4         int i = 0, n = s.length(); 5         // Skip the leading spaces 6         while (i < n && isspace(s[i])) i++; 7         // Skip the sign 8         if (s[i] == '+' || s[i] == '-') i++; 9         // Check for the following significant parts10         int digits = 0, dots = 0;11         while (i < n && (isdigit(s[i]) || s[i] == '.')) {12             if (isdigit(s[i])) digits++;13             else dots++;14             i++;15         }16         if (digits < 1 || dots > 1) return false;17         if (i == n) return true;18         // Check for the exponential parts19         if (s[i] == 'e') {20             i++;21             if (i == n) return false;22             if (s[i] == '+' || s[i] == '-') i++;23             digits = 0;24             while (i < n && (isdigit(s[i]))) {25                 digits++;26                 i++;27             }28             if (digits < 1) return false;29         }30         // Skip the trailing spaces31         while (i < n && isspace(s[i])) i++;32         return i == n;33     }34 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4638620.html

你可能感兴趣的文章
数据类型的一些方法
查看>>
Mindjet MindManager 2019使用教程:
查看>>
游戏设计的基本构成要素有哪些?
查看>>
详解 CSS 绝对定位
查看>>
AOP
查看>>
我的友情链接
查看>>
NGUI Label Color Code
查看>>
.NET Core微服务之基于Polly+AspectCore实现熔断与降级机制
查看>>
vue组件开发练习--焦点图切换
查看>>
浅谈OSI七层模型
查看>>
Webpack 2 中一些常见的优化措施
查看>>
移动端响应式
查看>>
python实现牛顿法求解求解最小值(包括拟牛顿法)【最优化课程笔记】
查看>>
js中var、let、const的区别
查看>>
腾讯云加入LoRa联盟成为发起成员,加速推动物联网到智联网的进化
查看>>
从Python2到Python3:超百万行代码迁移实践
查看>>
Windows Server已可安装Docker,Azure开始支持Mesosphere
查看>>
简洁优雅地实现夜间模式
查看>>
react学习总结
查看>>
微软正式发布PowerShell Core 6.0
查看>>