首页 > 代码库 > Valid Number
Valid Number
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 { boolean isAnInteger(String s) { int LEN = s.length(); if (LEN == 0) return false; int i = 0; if (s.charAt(i) == '+' || s.charAt(i) == '-') { i++ ; if (i == LEN) return false; } for (; i < LEN; i++ ) { char c = s.charAt(i); if (c < '0' || c > '9') return false; } return true; } boolean isAnDouble(String s) { int LEN = s.length(); if (LEN == 0) return false; int i = 0; if (s.charAt(i) == '+' || s.charAt(i) == '-') { i++ ; if (i == LEN) return false; } int numPoint = 0; int numN = 0; for (; i < LEN; i++ ) { char c = s.charAt(i); if (c >= '0' && c <= '9') { numN++ ; continue; } if (c == '.') { numPoint++ ; continue; } return false; } return numN > 0 && numPoint <= 1; } public boolean isNumber(String s) { if (s == null) return false; s = s.trim(); int LEN = s.length(); if (LEN == 0) return false; int indexE = s.indexOf('e'); if (indexE < 0) return isAnDouble(s); if (indexE + 1 == LEN) return false; return isAnDouble(s.substring(0, indexE)) && isAnInteger(s.substring(indexE + 1)); } }
Valid Number
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。