- Valid Number
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.
Solution:
1. public class Solution {
2. public boolean isNumber(String s) {
3. if (s == null) return false;
4. 5. s = s.trim();
6. int n = s.length();
7. 8. if (n == 0) return false;
9. 10. // Define flags
11. int signCount = 0;
12. 13. boolean hasE = false;
14. boolean hasNum = false;
15. boolean hasPoint = false;
16. 17. // Go through the characters
18. for (int i = 0; i < n; i++) {
19. char c = s.charAt(i);
20. 21. // invalid character
22. if (!isValid(c)) return false;
23. 24. // digit
25. if (c >= '0' && c <= '9') hasNum = true;
26. 27. // e or E
28. if (c == 'e' || c == 'E') {
29. // e 之前一定要有数字
30. if (hasE || !hasNum) return false;
31. // e 不能作为最后一个
32. if (i == n - 1) return false;
33. 34. hasE = true;
35. }
36. 37. // decimal place
38. if (c == '.') {
39. // 小数点不能出现在 e 之后
40. if (hasPoint || hasE) return false;
41. // 小数点如果在最后一位出现,那么前面必须有要数字
42. if (i == n - 1 && !hasNum) return false;
43. 44. hasPoint = true;
45. }
46. 47. // signs
48. if (c == '+' || c == '-') {
49. // 不允许超过两个符号出现
50. if (signCount == 2) return false;
51. // 不允许符号在最后出现
52. if (i == n - 1) return false;
53. // 符号出现在中间的前提是前面有 e
54. if (i > 0 && !hasE) return false;
55. 56. signCount++;
57. }
58. }
59. 60. return true;
61. }
62. 63. boolean isValid(char c) {
64. return c == '.' || c == '+' || c == '-' || c == 'e' || c == 'E' || c >= '0' && c <= '9';
65. }
66. }
