LeetCode Valid Number

来源:互联网 发布:办公软件office考试 编辑:程序博客网 时间:2024/05/16 08:27

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++;elsereturn 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>


0 0
原创粉丝点击