Valid Number
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.
思路:此题是真的有些难度的,并且最重要的是我根本就不清楚一个有效数字的规则。。
。
一个连规则都不知道的人怎么能玩好游戏呢,所以果断的挂了10次8次的。最后还是没有全然答对。
临时把别人的代码拿出来放在以下。有时间再好好研究一下:
public class Solution {
public boolean isNumber(String s) {
// Start typing your Java solution below
// DO NOT write main() function
/* "0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"+-2e10" => true
//*/
//check input.
if(s==null || s.length()==0) return false;
int sz = s.length();
int i=0; while(i<sz && s.charAt(i)==' ') ++i; boolean space = false;
boolean exp = false;
boolean dot = false;
boolean number = false;
boolean neg = false; for(; i<sz; i++) {
char c = s.charAt(i);
if(c==' ') {
space = true;
} else if(space==true) {
return false;
} else if( (c=='e' || c=='E') && exp==false && number==true) {
exp = true;
number = false;
dot = true;
neg = false;
} else if( c=='.' && dot==false) {
dot = true;
neg = true;
// number = false;
} else if( c>='0' && c<='9') {
number = true;
} else if((c=='+' || c=='-') && neg==false && number==false ) {
neg = true;
} else {
return false;
}
}
return number;
}
}