题目:
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,e后面不能有小数点第一位或最后一位可以为小数点,+/-只能出现在第一位或者e后面的第一位。
代码:
class Solution { public boolean isNumber(String s) { //判断一个字符串是不是合法的数字 s = s.trim(); boolean pointSeen = false; boolean eSeen = false; boolean isNumber = false; for(int i=0;i<s.length();i++){ char temp = s.charAt(i); if(temp>=‘0‘ && temp<=‘9‘){ isNumber = true; }else if(temp == ‘.‘){ if(eSeen || pointSeen) return false; pointSeen = true; }else if(temp == ‘e‘){ if(eSeen || !isNumber) return false; eSeen = true; isNumber = false; }else if(temp == ‘+‘ || temp==‘-‘){ //只能在首位或者isNumber后面为+/- if(i!=0 && s.charAt(i-1)!=‘e‘ ) return false; isNumber = false; }else return false; } return isNumber; } }
原文地址:https://www.cnblogs.com/271934Liao/p/8244594.html
时间: 2024-10-17 16:20:18