Title Link: Valid number
Validate if a given string is numeric.
Some Examples:
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
The requirement of this question is to determine whether the 1 string is a number.
string processing, but there are several details to note:
- Numbers can have leading and trailing spaces, but spaces are not allowed in the middle of a number;
- For '. ', the maximum allowed is 1 times, the front can have no number, but must have a number behind;
- For ' E ', it is allowed to appear at most 1 times, and must have numbers before and after it, but it is an integer, which cannot appear '. ' ;
- For ' + ' and '-', ' e ' is allowed to appear up to 1 times before and after, and must appear at the front of the number;
- As for the other characters, only the number (0~9) is allowed.
Here are a few examples:
"e" => false"." => false" " => false".1" => true"0e" => false"e9" => false"7e+6" => true"6+1" => false
Time complexity: O (N)
Space complexity: O (1)
1 class Solution2 {3 Public:4 BOOL Isnumber(string s)5 {6 int I = 0;7 //Skip leading spaces8 for( ; I < s.size() && "' == s[I]; ++ I);9 //Process signTen if(' + ' == s[I] || '-' == s[I]) One ++ I; A //Process The following number part - BOOL Digit = false, Dot = false, Exp = false; - for( ; I < s.size(); ++ I) the { - if('. ' == s[I] && !Dot) //'. ' Cannot appear 2 times, '. ' There can be no numbers in front - Dot = true; - Else if(' E ' == s[I] && !Exp && Digit) //' E ' cannot appear 2 times, ' E ' must be preceded by a number + { - //' E ' cannot appear after '. ', after ' e ' must be an integer (can be positive or negative) + Dot = Exp = true; A if(I + 1 < s.size() && (' + ' == s[I + 1] || '-' == s[I + 1])) at ++ I; - if(I + 1 >= s.size() || !(s[I + 1] >= ' 0 ' && s[I + 1] <= ' 9 ')) - return false; - } - Else if(s[I] >= ' 0 ' && s[I] <= ' 9 ') - Digit = true; in Else - Break; to } + - //Skip back spaces the for( ; I < s.size() && "' == s[I]; ++ I); * $ return Digit && I == s.size();Panax Notoginseng } - };
Reprint please indicate source: Leetcode---65. Valid number
Leetcode---65. Valid number