您的位置:首页 > 其它

leetcode---Valid Number

2014-12-22 20:21 288 查看
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.

其实这道题目并不难   只要 考虑好  几个 特殊字符出现的位置的条件就好了  不需要  他复杂的考虑  

public class Solution {
public boolean isNumber(String s) {
s = s.trim(); //去掉两头的空格 真是醉了
if (s.length() == 0) return false;
boolean hasE = false;
boolean hasDot = false;
boolean hasNumber = false;

for (int i = 0; i < s.length(); i++) {
// e cannot be the first character
if (i == 0 && s.charAt(i) == 'e') return false;
if (s.charAt(i) == 'e') { //e字符不能够有两个 以及不能够在数字没出现之前出现e
// e cannot be replicated nor placed before number
if (hasE == true || hasNumber == false) {
return false;
} else {
hasE = true;
}
}

if (s.charAt(i) == '.') {
// '.' cannot be replicated nor placed after 'e' 小数点 要在数字出现的后面并且不能够在E出现的后面出现
if (hasDot == true || hasE == true) {
return false;
} else {
hasDot = true;
}
}
// the sign can be placed at the beginning or after 'e' 正负号只能出现在开始以及E的后面一位
if (i != 0 && s.charAt(i - 1) != 'e' && (s.charAt(i) == '+' || s.charAt(i) == '-')) return false;

// no other chacraters except '+', '-', '.', and 'e'
if ((s.charAt(i) > '9' || s.charAt(i) < '0') && s.charAt(i) != '+' && s.charAt(i) != '-' && s.charAt(i) != '.' && s.charAt(i) != 'e')
return false;

// check whether numbers are included.
if (s.charAt(i) <= '9' && s.charAt(i) >= '0') {
hasNumber = true;
}
}
// '+', '-', and 'e' cannot be the last character
if (s.charAt(s.length() - 1) == '-' || s.charAt(s.length() - 1) == '+' || s.charAt(s.length() - 1) == 'e') return false;

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