65. Valid Number
阿新 • • 發佈:2022-04-06
For this problem, we need to consider the following cases:
- +23 - valid
- 23+5 - invalid
- 9e - invalid
- e6 - invalid
- 23e+5 - valid
- 9.6e2 - valid
- 9e6.2 - invalid
- 9e6e2 - invalid
- 9.9.1 - invalid
- +.2 valid
- .99 valid
- 66. valid
class Solution { boolean dotShow = false; boolean eShow= false; booleandigitShow = false; public boolean isNumber(String s) { s = s.trim(); for(int i=0; i<s.length(); i++) { if(s.charAt(i) == '-' || s.charAt(i) == '+') { if(i != 0 ) return false; } else if(Character.isDigit(s.charAt(i))) { digitShow= true; } else if(s.charAt(i) == '.') { if(eShow || dotShow) return false; dotShow = true; } else if(s.charAt(i) == 'e'||s.charAt(i)=='E') { if(eShow || !digitShow) return false; digitShow= false; eShow = true; return isNumber(s.substring(i+1)); //if the char is 'e' or 'E', check whether the string after 'e'/'E' is a valid number,
//but the '.', 'e' cannot appear any more, and at least one digit must appear. } else return false; } return numberSeen; } }