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 <regex>
2#include <string>
3#include <iostream>
4
5bool isNumber(std::string s) {
6 std::regex pattern("^[\+-]?((\d+\.?|\.\d)\d*)([eE][\+-]?\d+)?$");
7 return std::regex_match(s, pattern);
8}
9
10int main() {
11 std::cout << isNumber("53.5e93") << std::endl; // 1
12 std::cout << isNumber("1a") << std::endl; // 0
13 return 0;
14}
C++ provides the regex library which allows easy matching of the string against a regular expression pattern. This solution checks for valid number patterns like optional signs, decimal points, and exponents.
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.
1#include
This solution iteratively traverses the characters, checking the rules of valid numbers such as digits, signs, dots, and exponents. It carefully handles different cases to validate the string.