Title Link: Valid-number
/** * Validate If a given string is numeric. Some examples: "0" = True "0.1" + true "abc" = FALSE "1 A" + false "2e10" = = Truenote:it is intended for The problem statement to be ambiguous. You should gather all requirements up front before implementing one. * */public class ValidNumber {//1481/1481 test cases passed.//status:accepted//runtime:214 ms//submitted:0 minutes AG o//time complexity O (n) space complexity O (1) Public boolean isnumber (String s) {int i = 0;s = S.trim ();//Remove both ends of the space Boolean hasdecimal = false; Flag whether the decimal point (.) has occurred Boolean hasnum = false; Whether the string before the tag is a numeric value, Boolean HasE = false; Whether the token has already appeared (e) character if (s.length () = = 0) Return false;//determine if there is a positive sign character if (Issign (S.charat (0))) {i++;} while (I < s.length ()) {char c = s.charat (i), if (IsDigit (c)) {if (!hasnum) {hasnum = true;}} else if (Isdecimal (c)) {if (Hasdecimal | | hasE)//The entire value can only show one decimal points (.); The exponent of e cannot be a decimal; return false;hasdecimal = true;} else if (IsE (c)) {///if the previous character already appears (e) character, or (e) appears at the top or last of the entire character, then it is not a valid value if (HasE | |!hasnum | | (++i) >= s.length ()) return false;//determine if the exponent has a sign bit if (!issign (S.charat (i))) I--;hase = True;hasnum = false; Need to re-search for a value} Elsereturn false; If there are characters other than (numbers, decimal points, characters e) i++;} return hasnum; } public boolean issign (char c) {return c = = ' + ' | | c = = '-'; } public boolean isdigit (char c) {return (C-' 0 ' >= 0 && C-' 0 ' <= 9);} public boolean isdecimal (char c) {return c = = '. '; } public boolean IsE (char c) {return c = = ' E '; public static void Main (string[] args) {System.out.println (New ValidNumber (). Isnumber ("0")); System.out.println (New ValidNumber (). Isnumber ("0.1")); System.out.println (New ValidNumber (). Isnumber ("abc")); System.out.println (New ValidNumber (). Isnumber ("1 A")); System.out.println (New ValidNumber (). Isnumber ("2e10")); System.out.println (New ValidNumber (). Isnumber (". 1")); System.out.println (New ValidNumber (). Isnumber ("6e6.5"));}}
[Leetcode 65] Valid number (lowest pass rate)