您的位置:首页 > 其它

LeetCode Valid Number

2016-01-09 12:41 288 查看
Description:

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.

Solution:

我这里写的复杂了,可以一个valid的number可以这么写

a.bec

abc都是整数,a和c可以带上符号。这么写了之后再判断就容易很多。

<span style="font-size:18px;">public class Solution {
public boolean isNumber(String s) {
s = s.trim();
if (s.length() == 0)
return false;
if (s.charAt(0) == '+' || s.charAt(0) == '-')
s = s.substring(1);
char ch;
int count_dot = 0, count_e = 0, count_num = 0;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (ch == '.') {
if (count_dot == 0)
count_dot++;
else
return false;
} else if (ch >= '0' && ch <= '9') {
count_num++;
} else if (ch == '-') {
if (i != 0)
return false;
} else if (ch == 'e' && i > 0 && i + 1 < s.length()) {

for (int j = i + 1; j < s.length(); j++) {
if ((s.charAt(j) == '+' || s.charAt(j) == '-')
&& (j == i + 1) && (j + 1 < s.length()))
continue;
else if (s.charAt(j) < '0' || s.charAt(j) > '9')
return false;
}
if (count_num == 0)
return false;
return true;
} else {
return false;
}
}
if (count_num == 0)
return false;
return true;
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: