首页 > 代码库 > 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.
方法
分以下几个步骤:
1. 将字符串的最前面和最后面的空格去掉。2. 判断是否有e,并根据有e的情况进行判断:e前面是浮点,e后面必须是整形。PS:可以将使用小数点和e将字符串划分成3部分,进行判断,只需要遍历一遍字符串。3. 没有e,则判断整个字符串是不是浮点。注意字符串前面的正负号别忘了。可以参考:http://blog.csdn.net/sunbaigui/article/details/8981356private boolean isDouble(String s) { if (s.charAt(0) == '-' || s.charAt(0) == '+') { if (s.length() == 1) { return false; } else { s = s.substring(1); } } int len = s.length(); boolean hasPoint = false; boolean pointNext = false; boolean pointPre = false; for(int i = 0; i < len; i++) { char cur = s.charAt(i); if (cur == '.') { if (hasPoint) { return false; } else { hasPoint = true; } } else if (cur>= '0' && cur <= '9') { if (hasPoint) { pointNext = true; } else { pointPre = true; } } else { return false; } } if (hasPoint && (pointNext == false && pointPre == false)) { return false; } else { return true; } } private boolean isInteger(String s) { if (s.charAt(0) == '-' || s.charAt(0) == '+') { if (s.length() == 1) { return false; } else { s = s.substring(1); } } int len = s.length(); for (int i = 0; i < len; i++) { char cur = s.charAt(i); if (!(cur>= '0' && cur <= '9')) { return false; } } return true; } public boolean isNumber(String s) { if (s == null || s.length() == 0) { return false; } // while(!s.equals("") && s.charAt(0) == ' ') { s = s.substring(1); } while(!s.equals("") && s.charAt(s.length() - 1) == ' ') { s = s.substring(0, s.length() - 1); } if (s.equals("")) { return false; } int len = s.length(); for (int i = 0; i < len; i++) { char cur = s.charAt(i); if (cur == 'e') { if ((i == 0 || i == len - 1)) { return false; } else { return isDouble(s.substring(0, i)) && isInteger(s.substring(i + 1)); } } } return isDouble(s); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。