Validate if a given string is numeric.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
题解:题目不难,就是有点麻烦,要注意的地方很多,总结一下:
代码如下:
1 public class Solution { 2 public boolean isNumber(String s) { 3 if(s == null || s.length() == 0) 4 return false; 5 6 s = s.trim(); 7 if(s.length() == 0) 8 return false; 9 10 int i = 0; 11 if(s.charAt(0) == ‘+‘ || s.charAt(0) == ‘-‘) 12 i++; 13 14 boolean hasDot = false; 15 boolean hasExp = false; 16 boolean num = false; 17 18 while(i<s.length()){ 19 char now = s.charAt(i); 20 if(now >= ‘0‘ && now <= ‘9‘) 21 { 22 num = true; 23 } 24 else if(now == ‘.‘){ 25 if(hasDot || hasExp) 26 return false; 27 hasDot = true; 28 } 29 else if(now == ‘e‘){ 30 if(hasExp || num == false) 31 return false; 32 hasExp = true; 33 num = false; 34 } 35 else if(now == ‘+‘ || now == ‘-‘){ 36 if(s.charAt(i-1) != ‘e‘) 37 return false; 38 } 39 else 40 return false; 41 i++; 42 } 43 return num; 44 } 45 }
【leetcode刷题笔记】Valid Number,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/sunshineatnoon/p/3863777.html