Valid Number Java Solution


  • 0
    S

    Please let me know if you need more explaination, here is the code which I think is self-explanatory:

    public class Solution {
        public boolean isNumber(String s) {
            int start = 0, end = s.length()-1;
            // Remove whitespace from the beginning as well as the end
            while(start<s.length() && s.charAt(start)==' ') start++;
            while(end>=0 && s.charAt(end)==' ')   end--;
            // If only whitespace
            if(end<start)   return false;
            // System.out.println(start+" "+end);
            s = s.substring(start, end+1);
            // System.out.println(s);
            return isNumberUtil(s.toCharArray());
        }
        
        boolean isNumberUtil(char[] number){
            if(number == null || number.length==0)  return false;
            int nDots=0, nEs=0;
            boolean isNumSeen=false;
            // Make sure number starts with +, -, . or a digit
            if(!(number[0]=='+' || number[0]=='-' || number[0]=='.'||(number[0]>='0' && number[0]<='9'))){
                return false;
            }
            // System.out.println(number[0]);
            int start = 0;
            if(number[0]=='+' || number[0] == '-' || number[0]=='.'){
                start++;
                if(number[0] == '.'){
                    nDots++;
                }
            }
            // There has to be atleast one digit somehwere
            if(start==number.length)    return false;
            while(start<number.length){
                
                // for cases like 2e3.5(true) 2.e35(true) 46e.3(false), e cannot be before all digits 
                if(!((number[start]>='0' && number[start]<='9')||(nDots==0 && number[start]=='.' && nEs==0) ||(nEs==0&&nDots<=1&&isNumSeen&&number[start]=='e' ) )){
                    return false;
                }
                if(number[start]=='.'){
                    nDots++;
                    // if . comes after +, -, e and there is nothing after that
                    if(start>0 && (number[start-1] == 'e'||number[start-1] == '+'||number[start-1] == '-') &&start+1==number.length){
                        return false;
                    }
                }
                else if(number[start]=='e'){
                    // e is succeeded by + and - and then digits or .
                    if(start<number.length-1 && (number[start+1]=='-' || number[start+1] == '+')){
                        start++;
                    }
                    if(start==number.length-1)    return false;
                    nEs++;
                }
                else isNumSeen=true;
                start++;
            }
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.