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 shoshould gather all requirements up front before implementing one.
Https://oj.leetcode.com/problems/valid-number/
Train of Thought 1: process it directly. The general idea is to separate integers and decimals according to '.', and then determine each other. The situation is slightly complicated.
Train of Thought 2: automated machine, build a transfer function, and the code is easy to understand.
Idea 3 (lazy): Write the regular expression directly (in fact, the regular expression matching is also an automatic mechanism ).
public class Solution { public boolean isNumber(String s) { if (s.trim().isEmpty()) { return false; } String regex = "[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?"; if (s.trim().matches(regex)) { return true; } else { return false; } } public static void main(String[] args) { System.out.println(new Solution().isNumber("0")); System.out.println(new Solution().isNumber("0.1")); System.out.println(new Solution().isNumber(".1")); System.out.println(new Solution().isNumber("0.")); System.out.println(new Solution().isNumber(".")); System.out.println(new Solution().isNumber("abc")); System.out.println(new Solution().isNumber("1 a")); System.out.println(new Solution().isNumber("2e10")); }}
View code
Refer:
Http://jane4532.blogspot.com/2013/09/valid-numberleetcode.html
Http://www.cnblogs.com/chasuner/p/validNumber.html
Http://leetcodenotes.wordpress.com/2013/11/23/leetcode-valid-number/
Http://codeganker.blogspot.com/2014/04/valid-number-leetcode.html