Leetcode 65. Valid Number

Problem Explanation:

The problem criteria is to determine if a given string can be interpreted as a decimal number. For instance, "0" and "0.1" are valid decimal representations. On the contrary, strings like "abc" or "1 a" should return false. Characters that can be included in a valid decimal number include:

  • Numbers 0-9
  • Exponent - "e"
  • Positive/negative sign - "+"/"-"
  • Decimal point - "."

However, the combination of these characters forming a valid double representation is what truly matters. For example, "99e2.5" should return false as the exponent "e" is followed by a decimal number, which is not acceptable.

Solution Approach:

We create an iterative function that checks each character in the input string after trimming leading and trailing whitespaces.

  • If we encounter a decimal point (.), we must ensure we have not seen a decimal point or the exponent letter (e) prior to this, if we have then this is not a valid string.
  • If we encounter e, we must ensure we have not already seen e and we have seen a number before e. Post e, we reset the seen number flag to track number value after e.
  • For '+' and '-', they must be either at the beginning or they must be immediately after e. Post them, we reset the seen flag for numbers.
  • Finally, for every other character that is not a digit, we return false.

If after iterating through the string, we have encountered atleast one number, we return true. Else false.

Solution:

C++

1
2cpp
3  class Solution {
4  public:
5      bool isNumber(string s) {
6          /* Removing leading and trailing whitespaces */
7          s.erase(0, s.find_first_not_of(' '));
8          s.erase(s.find_last_not_of(' ') + 1);
9
10          /* Flags to track number, dot, and exponent */
11          bool seenNum = false;
12          bool seenDot = false;
13          bool seenE = false;
14
15          /* Iterating through each character in the string */
16          for (int i = 0; i < s.length(); ++i) {
17              switch (s[i]) {
18                  case '.':
19                      /* If dot or exponent encountered earlier, return false */
20                      if (seenDot || seenE)
21                          return false;
22                      seenDot = true;
23                      break;
24                  case 'e':
25                  case 'E':
26                      /* If exponent encountered earlier or no range number before e, return false */
27                      if (seenE || !seenNum)
28                          return false;
29                      seenE = true;
30                      seenNum = false; /* Resetting number flag to track number after e */
31                      break;
32                  case '+':
33                  case '-':
34                      /* If not beginning and sign immediately after e, return false */
35                      if (i > 0 && s[i - 1] != 'e')
36                          return false;
37                      seenNum = false; /* Resetting number flag to track number after sign */
38                      break;
39                  default:
40                      /* If not a digit, return false */
41                      if (!isdigit(s[i]))
42                          return false;
43                      seenNum = true;
44              }
45          }
46          /* If no numbers encountered, return false */
47          return seenNum;
48      }
49  };

(to be continued with Python, Java, JavaScript, and C# solutions...)### Python

1
2python
3  class Solution:
4    def isNumber(self, s: str) -> bool:
5        seen_numeric = False
6        seen_exponent = False
7        seen_dot = False
8
9        s = s.lstrip().rstrip()
10
11        for i in range(0, len(s)):
12            if s[i] == 'e':
13                if seen_exponent or not seen_numeric:
14                    return False
15                seen_exponent = True
16                seen_numeric = False
17            elif s[i] in ['+', '-']:
18                if i > 0 and s[i - 1] != 'e':
19                    return False
20            elif s[i] == '.':
21                if seen_dot or seen_exponent:
22                    return False
23                seen_dot = True
24            elif s[i].isdigit():
25                seen_numeric = True
26            else:
27                return False
28
29        return seen_numeric

Java

1
2java
3  class Solution {
4    public boolean isNumber(String s) {
5        s = s.trim();
6
7        boolean seenNum = false;
8        boolean seenE = false;
9        boolean seenDot = false;
10
11        for(int i=0; i<s.length(); i++) {
12            char c = s.charAt(i);
13
14            if(c >= '0' && c <= '9') {
15                seenNum = true;
16            } else if(c == 'e') {
17                if(seenE || !seenNum) {
18                    return false;
19                }
20                seenNum = false;
21                seenE = true;
22            } else if(c == '.') {
23                if(seenDot || seenE) {
24                    return false;
25                }
26                seenDot = true;
27            } else if(c == '+' || c == '-') {
28                if(i != 0 && s.charAt(i-1) != 'e') {
29                    return false;
30                }
31            } else {
32                return false;
33            }
34        }
35
36        return seenNum;
37    }
38  }

JavaScript

1
2javascript
3  var isNumber = function(s) {
4    s = s.trim();
5
6    var seenNum = false;
7    var seenE = false;
8    var seenDot = false;
9
10    for (var i = 0; i < s.length; i++) {
11        if (s[i] >= '0' && s[i] <= '9') {
12            seenNum = true;
13        } else if (s[i] === 'e') {
14            if (seenE || !seenNum) {
15                return false;
16            }
17            seenNum = false;
18            seenE = true;
19        } else if (s[i] === '.') {
20            if (seenDot || seenE) {
21                return false;
22            }
23            seenDot = true;
24        } else if (s[i] === '+' || s[i] === '-') {
25            if (i != 0 && s[i - 1] != 'e') {
26                return false;
27            }
28        } else {
29            return false;
30        }
31    }
32
33    return seenNum;
34  };

Using these solutions, we can effectively check whether given strings can be interpreted as valid decimal numbers in several programming languages, including Python, Java, JavaScript, and even C++. The approach in each language uses logical checks against each character within the input string, preserving the order and mostly using the same overall methodology.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫