您的位置:首页 > 其它

LeetCode #65 Valid Number

2015-08-02 20:06 274 查看
Validate if a given string is numeric.

Some examples:

"0"
=>
true


" 0.1 "
=>
true


"abc"
=>
false


"1 a"
=>
false


"2e10"
=>
true


Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

leetcode将本题的 Difficulty 定义为Hard,其实本题在Leetcode中并不能称上是难题,但本题确实需要注意很多细节,所以代码很容易出错。顺便说下,直到现在,本题在leetcode上的通过率也还是最低的(如下)。



<pre name="code" class="cpp">class Solution {
public:
bool isNumber(string s) {

if(s.size() == 0) return false;

int index = 0, num_cnt = 0, dot_cnt = 0;

while(s[index] == ' ') index++;

if(s[index] == '+' || s[index] == '-') index++;

while(isdigit(s[index]) || s[index] == '.') s[index++] == '.' ? dot_cnt++ : num_cnt++;

if(dot_cnt > 1 || num_cnt < 1) return false;

if(s[index] == 'e'){
index++; num_cnt = 0; dot_cnt = 0;
if(s[index] == '+' || s[index] == '-') index++;
while(isdigit(s[index]) || s[index] == '.') s[index++] == '.' ? dot_cnt++ : num_cnt++;
if(dot_cnt > 0 || num_cnt < 1) return false;
}

while(index < s.size()){
if(s[index++] != ' ') return false;
}
return true;
}
};



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: