Tuesday, September 16, 2014

Leetcode: Valid Number

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.
Understand the problem:
The problem asks for determining if a given string is numeric. The challenge part of the problem is to consider each and every corner cases.

  • If the string starts from number, it returns true;
  • If the string starts from empty spaces, skip all the empty spaces;
  • If the string starts from non-numbers, return false;
  • If the string has white space in between, return false;
  • If the first part of the string is numerical, return true.
Based on the analysis above, we can solve it the problem by the following steps:

  1. First check if the string is null or empty. Return false if the string is null or empty
  2. First check the leading white spaces, simply skip them. Be careful if the string contains only white spaces
  3. Then check the sign next, if it is "+" or '-', go to next;
  4. Check the dot character ' . '
  5. The next character must be a numerical number. If not, simply return false.
  6. Iterate until we reach the first non-numerical character in the string. Note that "1   " is true by "1   a" is false; 

No comments:

Post a Comment