DEV Community

Cover image for Valid Number
Oluwanifemi Latunde
Oluwanifemi Latunde

Posted on

Valid Number

Today marks the last day of the #I4G10DaysOfCodeChallenge. Today's challenge featured validating an array of numbers.

Problem:
A valid number can be split up into these components (in order):

  1. A decimal number or an integer.
  2. (Optional) An 'e' or 'E', followed by an integer.

A decimal number can be split up into these components (in order):

  1. (Optional) A sign character (either '+' or '-').
  2. One of the following formats:
    1. One or more digits, followed by a dot '.'.
    2. One or more digits, followed by a dot '.', followed by one or more digits.
    3. A dot '.', followed by one or more digits.

An integer can be split up into these components (in order):

  1. (Optional) A sign character (either '+' or '-').
  2. One or more digits.
For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].
Enter fullscreen mode Exit fullscreen mode

Approach:

Basic Checks:

  • We know that a valid number cannot have more than 1 decimal point, so we declare a variable to store if the decimal has been used or not. The initial value is False.
  • Also, we need to have at least one integer for the number to be valid. We can have alphabet 'e' or 'E', but a number needs to be after it.

  • Next we have a while loop, and iterate each character as we go along and if we get anything that is invalid, we return False.

  • Otherwise we keep going till the end of the string and if we have seen at least one number then it means our number is valid.

Top comments (0)