For this problem, we need to consider the following cases:

  1. +23 - valid
  2. 23+5 - invalid
  3. 9e - invalid
  4. e6 - invalid
  5. 23e+5 - valid
  6. 9.6e2  - valid
  7. 9e6.2 - invalid
  8. 9e6e2 - invalid
  9. 9.9.1 - invalid
  10. +.2 valid
  11. .99 valid
  12. 66. valid
class Solution {
    boolean dotShow = false;
    boolean eShow= false;
    boolean digitShow = 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; } }

 

posted on 2022-04-06 13:08  阳光明媚的菲越  阅读(8)  评论(0编辑  收藏  举报