Valid Number
Validate if a given string is numeric.
Example
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
考察 corner case
public class Solution { /** * @param s the string that represents a number * @return whether the string is a valid number */ public boolean isNumber(String s) { if (s == null || s.length() == 0) { return false; } String str = s.trim(); if (str.length() == 0) { return false; } boolean num = false; boolean exp = false; boolean dot = false; int i = 0; if (str.charAt(i) == '+' || str.charAt(i) == '-') { ++i; } while (i < str.length()) { char c = str.charAt(i); if (Character.isDigit(c)) { num = true; }else if (c == '.') { if (dot || exp) { return false; } dot = true; }else if (c == 'e') { if (exp || num == false) { return false; } exp = true; num = false; }else if (c == '+' || c == '-') { if (str.charAt(i - 1) != 'e') { return false; } }else { return false; } ++i; } return num; } }

浙公网安备 33010602011771号