Leetcode Valid Number

Source: Internet
Author: User

(I wrote a water question on leetcode with my teammates)

Portal

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.

Solution:

Test instructions is to judge if a string is not a valid real number (double literal) and actually wants you to implement Istream::istream &operator>> (const double &)(for C + +).

We can certainly hand-code out this function, but it is better to use some flag (member function) dose his own medicine of the IStream class.

Implementation:

1 classSolution {2  Public:3     BOOLIsnumber (strings) {4         intb=0, e=s.size ();5          for(; Isspace (S[b]); b++);6          for(; Isspace (s[e-1]); e--);7         stringT=s.substr (b, E-b);8         if(*t.rbegin ()! ='.'&&!isdigit (*t.rbegin ()))return false;9         if(*t.rbegin () = ='.'&&!isdigit (* (T.rbegin () +1)))return false; Ten StringStream x (t); One         Doubley; AX>>y; -         returnx.eof (); -     } the};

This is probably by far the shortest C + + implementation (if not regular expression) ... Escape

If the range of double in C + + is sufficiently large, it can be achieved even shorter:

1 classSolution {2  Public:3     BOOLIsnumber (strings) {4         intb=0, e=s.size ();5          for(; Isspace (S[b]); b++);6          for(; Isspace (s[e-1]); e--);7StringStream x (s.substr (b, Eb));8         Doubley;9X>>y;Ten         return!x.fail () &&x.eof (); One     } A};

Leetcode Valid Number

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.