您的位置:首页 > 其它

Valid Number

2015-09-09 22:01 393 查看
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.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

思路:这道题目就是可能的情况太多了,数字的格式是:

【空白】【符号(+-)】【数字】【小数点】【数字】【e】【符号】【数字】【空白】

其中不能出现一下情况:

(1)全是空白

(2)【e】【符号】【数字】【空白】(e前面的系数不存在)

(3)【小数点】【e】【符号】【数字】【空白】(e前面的系数只是小数点)

(4)【空白】【符号】【小数点】【空白】(小数点前后没有数字)

(5)【空白】【符号(+-)】【数字】【小数点】【数字】【e】【符号】(e后面没有数字)

代码如下:

class Solution {
public:
bool isAllBlank(string s){//s是否全是空白
for(int i = 0; i < s.length(); ++i)
if(!isblank(s[i]))
return false;
return true;
}
bool faceE(string s){//碰到e的处理
int i = 0;
int len = s.length();
if(s[0] == '-' || s[0] == '+')
i++;
if(isdigit(s[i])){
i++;
while(i < len && isdigit(s[i]))
i++;
return isAllBlank(s.substr(i));
}
return false;
}
bool faceDot(bool hasDigit, string s){//碰到小数点的处理,hasDigit表示小数点之前是否出现数字
int i = 0, len = s.length();
if(isdigit(s[i])){
i++;
while(i < len && isdigit(s[i]))
i++;
if(i == len)//全是数字
return true;
else if(s[i] == 'e' || s[i] == 'E')
return faceE(s.substr(i+1));
else if(isblank(s[i])){
return isAllBlank(s.substr(i+1));
}
else
return false;
}
else if(s[i] == 'e' || s[i] == 'E')
return hasDigit && faceE(s.substr(i+1));
else if(isblank(s[i])){
return isAllBlank(s.substr(i+1));
}
else
return false;
}
bool isNumber(string s) {
int i = 0, countDot = 0, len = s.length();
bool hasDigit = false;
while(i < len && isblank(s[i]))
i++;
if(i == len)//过滤空白
return false;
if(s[i] == '-' || s[i] == '+')
i++;
while(i < len && isdigit(s[i])){//过滤数字
i++;
hasDigit = true;
}
if(i == len)
return true;
if(s[i] == '.'){//碰到小数点
if(!hasDigit && isAllBlank(s.substr(i+1)))
return false;
else if(hasDigit && isAllBlank(s.substr(i+1)))
return true;
else
return faceDot(hasDigit, s.substr(i+1));
}
else if(hasDigit && (s[i] == 'E' || s[i] == 'e')){//碰到e
return faceE(s.substr(i+1));
}

else if(isblank(s[i])){
return isAllBlank(s.substr(i+1));
}
else
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: