Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public boolean isNumber(String s) {
- if(s == null) return false;
- s = s.trim();
- if(s.length() < 1) return false;
- for(char ch : s.toCharArray())
- {
- if(Character.isDigit(ch) || ch == '.' || ch == 'e' || ch == '+' || ch == '-') continue;
- return false; // invalid for any other characters
- }
- // now try to separate s into two parts
- int pos = s.indexOf('e');
- if(pos < 0) return parseD(s) || parseI(s);
- String sub1 = s.substring(0, pos), sub2 = s.substring(pos + 1);
- int l1 = sub1.length(), l2 = sub2.length();
- if(l1 < 1 || l2 < 1) return false;
- return (parseD(sub1) || parseI(sub1)) && parseI(sub2);
- }
- boolean parseD(String s)
- {
- int pos = s.indexOf('.');
- if(pos < 0)
- {
- return parseI(s);
- }
- // has dot
- /*
- possible forms
- [sign] #.#
- [] #.EMPTY
- []EMPTY.#
- */
- String sub1 = s.substring(0, pos), sub2 = s.substring(pos + 1);
- int l1 = sub1.length(), l2 = sub2.length();
- if(l1 < 1 && l2 < 1) return false; // EMPTY.EMPTY
- if(l2 < 1) return parseI(sub1); // [sign]#.EMPTY
- return sub1.matches("[+|-]?[\\d]*") && parseI0(sub2); // [sign]Empty.#
- }
- boolean parseI(String s)
- {
- // if(s.length() < 1) return true;
- if(s.charAt(0) == '+' || s.charAt(0) == '-') s = s.substring(1);
- return parseI0(s);
- }
- boolean parseI0(String s)
- {
- // System.out.println(s);
- // System.out.println(s.matches("\\d+"));
- return s.matches("\\d+");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment