A valid number can be split up into these components (in order):
- A decimal number or an integer.
- (Optional) An
'e'
or'E'
, followed by an integer.
A decimal number can be split up into these components (in order):
- (Optional) A sign character (either
'+'
or'-'
). - One of the following formats:
- One or more digits, followed by a dot
'.'
. - One or more digits, followed by a dot
'.'
, followed by one or more digits. - A dot
'.'
, followed by one or more digits.
- One or more digits, followed by a dot
An integer can be split up into these components (in order):
- (Optional) A sign character (either
'+'
or'-'
). - 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.
Example 1:
Input: s = "0" Output: true
Example 2:
Input: s = "e" Output: false
Example 3:
Input: s = "." Output: false
Example 4:
Input: s = ".1" Output: true
Constraints:
1 <= s.length <= 20
s
consists of only English letters (both uppercase and lowercase), digits (0-9
), plus'+'
, minus'-'
, or dot'.'
.
Solution: Rule checking
Time complexity: O(n)
Space complexity: O(1)
C++
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 28 29 30 31 32 33 34 35 |
// Author: Huahua class Solution { public: bool isNumber(string s) { for (int i = 0; i < s.length(); ++i) if (s[i] != ' ') { s = s.substr(i); break; } while (!s.empty() && s.back() == ' ') s.pop_back(); bool dot = false; bool e = false; bool digit = false; for (int i = 0; i < s.length(); ++i) { s[i] = tolower(s[i]); if (isdigit(s[i])) { digit = true; } else if (s[i] == '.') { if (e || dot) return false; dot = true; } else if (s[i] == 'e') { if (e || !digit) return false; e = true; digit = false; } else if (s[i] == '-' || s[i] == '+') { if (i != 0 && s[i - 1] != 'e') return false; } else { return false; } } return digit; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment