[Leetcode] valid number

Source: Internet
Author: User

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

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.