DEV Community

Ezekiel nwuguru
Ezekiel nwuguru

Posted on

DAY 10: VALID NUMBER

Hey! is day 10 of 10 days coding challenge with I4G. Today's task was to check if a given string is a valid number.

Thought process:
Understanding of the problem: The task here is to validate that an input is a valid number. A valid number can be:

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

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

  • (Optional) A sign character (either '+' or '-').

  • One of the following formats:

  • One or more digits, followed by a dot '.'.

  • One or more digits, followed by a dot '.', followed by one or more digits.

  • A dot '.', followed by one or more digits.

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

  • (Optional) A sign character (either '+' or '-').

  • One or more digits.

**Solution: **To solve this I employed two java library: regex matcher and regex pattern. The regex matcher check if a given input matches a given pattern. It returns true if it matches and false if it does not.

Algorithm:

  1. import regex matcher and regex pattern from java util library
  2. Trim the given string to remove white spaces and store it in the original string
  3. Check if string is empty, if so, return false.
  4. Instantiate the pattern class and declare the required pattern
  5. Instantiate the Matcher class and check if the string matches the given pattern.

checkout my code here: https://leetcode.com/problems/valid-number/submissions/812626535/

Top comments (0)