[LeetCode] Valid Number

65. Valid Number

A valid number can be split up into these components (in order):

  1. A decimal number or an integer.
  2. (Optional) An ‘e’ or ‘E’, followed by an integer.

A decimal number can be split up into these components (in order):

  1. (Optional) A sign character (either ‘+’ or ‘-‘).
  2. One of the following formats:
  1. One or more digits, followed by a dot ‘.’.
  2. One or more digits, followed by a dot ‘.’, followed by one or more digits.
  3. A dot ‘.’, followed by one or more digits.

An integer can be split up into these components (in order):

  1. (Optional) A sign character (either ‘+’ or ‘-‘).
  2. One or more digits.

For example, all the following are valid numbers: [“2”, “0089”, “-0.1”, “+3.14”, “4.”, “-.9”, “2e10”, “-90E3”, “3e+7”, “+6e-1”, “53.5e93”, “-123.456e789”], while the following are not valid numbers: [“abc”, “1a”, “1e”, “e3”, “99e2.5”, “—6”, “-+3”, “95a54e53”].

Given a string s, return true if s is a valid number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
bool isNumber(string s) {
bool sign = s[0] == '+' or s[0] == '-', e = false, dot = false, digit = false;
for(int i = sign; i < s.length(); i++) {
if(s[i] == '+' or s[i] == '-') {
if(sign) return false;
if(!e and i != 0) return false;
if(e and digit) return false;
sign = true;
} else if(isdigit(s[i])) {
digit = true;
} else if(s[i] == 'e' or s[i] == 'E') {
if(!digit) return false;
if(e) return false;
sign = false;
digit = false;
e = true;
} else if(s[i] == '.') {
if(e) return false;
if(dot) return false;
dot = true;
} else return false;
}
return digit;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/20/PS/LeetCode/valid-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.