Valid Number
2015-08-18 11:32
155 查看
问题描述
Validate if a given string is numeric.
Some examples:
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
解决思路
类似于这样的问题,说难也难,说容易也容易。
难的地方在于很难一次写出freebug的代码,容易的地方在于枚举规则,仅此一条思路而已。
大致需要注意的思路如下:
1. s = s.trim();
2. + / - 开头出现,e后面也可以出现;
3. ‘.’的位置,注意题目中的".01"也是合法的;
4. ‘001.1’这样的是否合法?
程序
附上 Test Case
Output
0 true
0.1 true
abc false
1 a false
2e10 true
0.1e-10 true
.01 true
e10 false
-1e-10 true
1e false
. false
3. true
.e1 false
4e+ false
46.e3 true
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.
解决思路
类似于这样的问题,说难也难,说容易也容易。
难的地方在于很难一次写出freebug的代码,容易的地方在于枚举规则,仅此一条思路而已。
大致需要注意的思路如下:
1. s = s.trim();
2. + / - 开头出现,e后面也可以出现;
3. ‘.’的位置,注意题目中的".01"也是合法的;
4. ‘001.1’这样的是否合法?
程序
public boolean isNumber(String s) { if (s == null || s.trim().length() == 0) { return false; } s = s.trim(); int idx = 0; if (s.charAt(idx) == '+' || s.charAt(idx) == '-') { ++idx; } if (idx >= s.length()) { return false; } boolean hasDot = false; boolean hasE = false; int dotIdx = idx; int eIdx = idx; for (int i = idx; i < s.length(); i++) { char c = Character.toLowerCase(s.charAt(i)); if (c == '.') { if (hasDot || hasE) { return false; } hasDot = true; dotIdx = i; continue; } if (c == 'e') { if (hasE) { return false; } if (hasDot && i - 1 == idx && Character.toLowerCase(s.charAt(i - 1)) == '.') { // .e return false; } hasE = true; eIdx = i; continue; } if (hasE && Character.toLowerCase(s.charAt(i - 1)) == 'e' && i != s.length() - 1 && (s.charAt(i) == '-' || s.charAt(i) == '+')) { // 1e+ continue; } if (!Character.isDigit(c)) { // 'a''b'... return false; } } if (hasDot) { if (s.substring(dotIdx + 1).length() == 0 && s.substring(idx, dotIdx).length() == 0) { // '.' return false; } } if (hasE) { if (s.substring(eIdx + 1).length() == 0) { return false; } if (s.substring(idx, eIdx).length() == 0) { return false; } } return true; }
附上 Test Case
String[] s = { "0", " 0.1", "abc", "1 a", "2e10", "0.1e-10", ".01", "e10", "-1e-10", "1e", ".", "3.", ".e1", "4e+", "46.e3" };
Output
0 true
0.1 true
abc false
1 a false
2e10 true
0.1e-10 true
.01 true
e10 false
-1e-10 true
1e false
. false
3. true
.e1 false
4e+ false
46.e3 true
相关文章推荐
- 【LeetCode】191. Number of 1 Bits
- MySQL诊断分析工具 Profiling 的使用[转载]
- js 判断本地文件
- 2015-8-18数据结构-分冶-整数划分问题
- 排序算法系列——冒泡排序
- web服务器:SOAP,WSDL,UDDI
- 天声人語 20150818
- hdu-1596-find the safest road(dijkstra)
- [分享] 安卓手机ROM和RAM的区别
- ZOJ 2601 Warehouse Keeper(费用流)
- MBA关注:长期太忙或太穷人会变傻
- 《Javascript权威指南》十六学习笔记:BOM资源---BOM基本应用
- 选美素数~~~~~~~(⊙o⊙)
- Hartals
- Linux文件系统相关知识整理
- nsight 使用caffe。
- MonoDevelop中文乱码
- Spring mvc 设置自定义首页
- 安装过程中出现PKG_CONFIG_PATH的问题解决方法
- windows 2008 R2 wincache 不稳定