第28题 Valid Number
来源:互联网 发布:承接工程项目软件 编辑:程序博客网 时间:2024/05/21 21:42
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.
public class Solution { public boolean isNumber(String s) { String sTrim = s.trim(); if(sTrim.length()==0) return false; if(sTrim.contains(" ")) return false; String pattern1 = "", pattern2 = ""; if(sTrim.contains("e")){ int indexE = sTrim.indexOf('e'); String beforeE="", afterE=""; if(indexE!=-1){ beforeE = sTrim.substring(0,indexE); afterE = sTrim.substring(indexE+1, sTrim.length()); indexE = sTrim.indexOf('e', indexE+1); if(indexE!=-1) return false; } pattern1 = "^[+,-]?[0-9]+$"; if(!afterE.matches(pattern1)) return false; if(beforeE.contains(".")){ pattern1 = "^[+,-]?[0-9]*[.]{1}[0-9]+$"; pattern2 = "^[+,-]?[0-9]+[.]{1}[0-9]*$"; if(beforeE.matches(pattern1)||beforeE.matches(pattern2)) return true; else return false; }else{ pattern1 = "^[+,-]?[0-9]+$"; if(beforeE.matches(pattern1)) return true; else return false; } } else{ if(sTrim.contains(".")){ pattern1 = "^[+,-]?[0-9]+[.]{1}[0-9]*$"; pattern2 = "^[+,-]?[0-9]*[.]{1}[0-9]+$"; if(sTrim.matches(pattern1)||sTrim.matches(pattern2)) return true; else return false; } else{ pattern1 = "^[+,-]?[0-9]+$"; if(sTrim.matches(pattern1)) return true; else return false; } }}
Note:
“.3”也算valid number!"3."也算valid number!但"."前后不可同时为空字符,所以要用或判断。
"7e69e"在java中用split分割,长度为2,最后不算第二个e后的空字符,所以不能检查如“e123e”格式的字符串。所以用indexOf函数查找字符"e",然后用substring获取"e"前后字符。string.indexOf('e',index)查找从string的index位置开始有无字符'e'。
科学计数法e后可以加+或-号,后面跟数字。
0 0
- 第28题 Valid Number
- Leetcode algorithms 第 65 题:Valid Number。
- LeetCode 第 65 题(Valid Number)
- Hard 65题 Valid Number
- 【leetcode】第65题 Valid Number 这道题用JS代码超级简单=-=
- Valid Number
- Valid Number
- Valid Number
- Valid Number
- Valid Number
- Valid Number
- Valid Number
- Valid Number
- Valid Number
- Valid Number
- Valid Number
- Valid Number
- Valid number
- spark ssh配置
- pscp使用记录
- AFNetworking超时时间设置
- 吴甘沙:大数据的十个技术前沿
- android listView中checkbox的使用
- 第28题 Valid Number
- Ajax入门----检测用户ID是否存在
- 深入Android通过Apache HTTP访问HTTP资源(一)(转)
- Eclipse就真的那么差吗?
- 给apache2.2加上mod_encoding模块後 php5.2.0 处理url出现bug
- Spring AOP进行日志记录,管理
- Ubuntu 手机开发培训准备
- 字符串习题
- java反射机制不支持可变参数