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.
1using System;
2using System.Text.RegularExpressions;
3
4class ValidNumber {
5 public static bool IsNumber(string s) {
6 string pattern = "^[\+-]?((\d+\.?|\.\d)\d*)([eE][\+-]?\d+)?$";
7 return Regex.IsMatch(s, pattern);
8 }
9 public static void Main() {
10 Console.WriteLine(IsNumber("53.5e93")); // True
11 Console.WriteLine(IsNumber("1a")); // False
12 }
13}
This C# solution uses the Regex
class which allows regex-based validation of the input string against number-like patterns.
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.
1using System;
2
class ValidNumberIterative {
public static bool IsNumber(string s) {
int n = s.Length;
int i = 0;
bool numSeen = false, dotSeen = false, eSeen = false;
while (i < n && s[i] == ' ') i++;
if (i < n && (s[i] == '+' || s[i] == '-')) i++;
while (i < n) {
if (char.IsDigit(s[i])) {
numSeen = true;
} else if (s[i] == '.') {
if (dotSeen || eSeen) return false;
dotSeen = true;
} else if (s[i] == 'e' || s[i] == 'E') {
if (eSeen || !numSeen) return false;
eSeen = true;
numSeen = false;
} else if (s[i] == '+' || s[i] == '-') {
if (s[i - 1] != 'e' && s[i - 1] != 'E') return false;
} else if (s[i] == ' ') {
while (i < n && s[i] == ' ') i++;
return i == n;
} else {
return false;
}
i++;
}
return numSeen;
}
public static void Main() {
Console.WriteLine(IsNumber("53.5e93")); // True
Console.WriteLine(IsNumber("1a")); // False
}
}
This C# iteration method processes each character and applies decision rules to confirm compliance with valid number forms, making sure it handles signs, dots, and exponents correctly.