Sponsored
Sponsored
A regular expression can be used to validate if a string is a valid number by matching patterns that define valid numbers. This pattern matches integers with optional signs, decimals, and scientific notation.
Time Complexity: O(n) due to scanning each character in the string.
Space Complexity: O(1) since we're using a fixed-size pattern.
1#include <stdio.h>
2#include <regex.h>
3#include <stdbool.h>
4
5bool isNumber(const char *s) {
6 regex_t regex;
7 int reti;
8 // Regular expression for matching a valid number
9 reti = regcomp(®ex, "^[\+-]?((\d+\.?|\.\d)\d*)([eE][\+-]?\d+)?$", REG_EXTENDED);
10 if (reti) {
11 fprintf(stderr, "Could not compile regex\n");
12 return false;
13 }
14 // Execute regular expression
15 reti = regexec(®ex, s, 0, NULL, 0);
16 regfree(®ex);
17 return !reti;
18}
19
20int main() {
21 printf("%d\n", isNumber("53.5e93")); // 1
22 printf("%d\n", isNumber("1a")); // 0
23 return 0;
24}
C language does not feature built-in regular expression checks. Therefore, this solution leverages the usage of the POSIX regex library to define patterns and match the string against it.
This approach involves parsing the string based on its characters and their positions. By iterating through the string, the method confirms whether it forms a valid number pattern based on segment rules.
Time Complexity: O(n) where n is the length of the string.
Space Complexity: O(1) using variables to track state.
1function isNumber
The JavaScript solution follows a similar approach as the other iterative solutions, using variable states to ensure the string adheres to valid number formats including both integer and decimal representations with optional exponents.