Valid Number

来源:互联网 发布:mac mini 音频输出 编辑:程序博客网 时间:2024/05/01 13:52

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 int index;public boolean isNumber(String s) {// Start typing your Java solution below// DO NOT write main() functionindex = 0;if(s.length() == 0)return false;// 去掉空格while(index < s.length() && s.charAt(index) == ' ')index++;// e 之前是否为数字if(!isNum(s, false))return false;// e 之后是否为数字if(index < s.length() && s.charAt(index) == 'e'){index++;if(!isNum(s, true))return false;}while(index < s.length() && s.charAt(index) == ' ')index++;if(index == s.length())return true;elsereturn false;}public boolean isNum(String s, boolean flag){boolean res = false;if(index < s.length() && (s.charAt(index) == '-' || s.charAt(index) == '+'))index++;boolean dot = false;while(index < s.length()){if(s.charAt(index) <= '9' && s.charAt(index) >= '0'){res = true;index++;}else if(s.charAt(index) == '.'){if(flag) // e 后面数字不带点return false;if(dot) // 多于一个点return false;dot = true;index++;}else if(s.charAt(index) == 'e' || s.charAt(index) == ' ')return res;elsereturn false;}return res;}}

One exceptional solution!

public class Solution {public boolean isNumber(String s) {if (s == null || s.length() == 0)return false;int index = 0;index = skipWhiteSpaces(s, index);index = skipSigns(s, index);int n1 = skipDigits(s, index);index += n1;if (index < s.length() && s.charAt(index) == '.')index++;int n2 = skipDigits(s, index);index += n2;if (n1 == 0 && n2 == 0)return false;if (index < s.length()&& (s.charAt(index) == 'e' || s.charAt(index) == 'E')) {index++;index = skipSigns(s, index);int n3 = skipDigits(s, index);if (n3 == 0)return false;index += n3;}index = skipWhiteSpaces(s, index);return index == s.length();}public int skipWhiteSpaces(String s, int index){while(index < s.length() && s.charAt(index) == ' ')index++;return index;}public int skipSigns(String s, int index){if(index < s.length() && (s.charAt(index) == '+' || s.charAt(index) == '-'))return index + 1;return index;}public int skipDigits(String s, int index){int counter = index;while(counter < s.length() && s.charAt(counter) >= '0' && s.charAt(counter) <= '9')counter++;return counter - index;}}


原创粉丝点击