Forty-seven daily algorithms: valid number (verify whether it is a number)

Source: Internet
Author: User

It is not easy to write this function correctly, because there are many things to consider:

1) There may be spaces before and after the string, but spaces are not allowed in the middle.

2) There may be decimal places, 1.235, or. 3522.

3) There may be exponential forms, 2e10 2e-1 AND OTHER FORMS

Validate if a given string is Numeric.

Some examples:
"0"=>true
" 0.1 "=>true
"abc"=>false
"1 a"=>false
"2e10"=>true

There are many restrictions to consider whether the string is in the numerical form. Therefore, we can use the form of a global variable to indicate whether this numeric form is valid again.

Then, query by bit to check whether the prerequisite debugging is true. If one of the conditions is not met, false is returned.

<span style="font-size:18px;">class Solution {public:    bool isNumber(const char *s) {        while (*s == ' ') ++s;        while (*s == '+' || *s == '-') ++s;        bool exp = false, space = false, point = false;        bool number = false;        while (*s != '\0') {            if (isdigit(*s)) {                if (space) return false;                else number = true;            } else if (*s == '.') {                if (!point && !space && !exp) {                    point = true;                } else {                    return false;                }            } else if (*s == 'e') {                if (!exp && number && !space) {                    exp = true;                    number = false;                    while (*(s+1) == '+' || *(s+1) == '-') ++s;                } else {                    return false;                }            } else if (*s == ' ') {                if (!space) {                    space = true;                }            } else {                return false;            }            ++s;        }        return number;    }};</span>











Forty-seven daily algorithms: valid number (verify whether it is a 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.