65. 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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

 

Hide Company Tags
 LinkedIn
Hide Tags
 Math String
Show Similar Problems
 
public class Solution {
    public boolean isNumber(String s) {
        // the key is to consider all the case;
        // +,- ,E,e, ., number no character.  
        // trim()
        // 1. +/- should be first  or after e/E like 2e-20 
        //          if +,- is the first then the next must be number 
        // 2. e/ E  there is no e/E before eflag and it should not be last one and before e should be number
        // 3. . there is no other dot before dotFlag.
        // 4. should be number
        // test 1 : +1 or 2E-20 :test 2 :2e test 3 0.9
        s = s.trim();
        if(s.length() == 0) return false;
        boolean dotFlag = false;
        boolean eFlag = false;
        boolean signFlag =false;
        boolean numFlag = false;
        char sArray[] = s.toCharArray();
        for(int i = 0 ; i < s.length(); i ++){
            if(sArray[i] == '+' || sArray[i] == '-'){
                if((i == 0 || sArray[i-1] == 'e' || sArray[i-1] == 'E' ) && ( i < s.length() - 1 && (sArray[i+1] >= '0' && sArray[i+1] <= '9' || sArray[i+1] == '.'))) { //+0.8 TRUE
                    continue;
                }
                else
                    return false;
            }
            else if(sArray[i] == 'e' || sArray[i] == 'E'){
                if(!numFlag || eFlag || i == s.length() - 1) return false;//care the first e like e9 false
                else eFlag = true;
            }
            else if(sArray[i] == '.'){
                if(eFlag || dotFlag || (!numFlag &&i == s.length() - 1))  return false; //.1 true 3.true
                else
                    dotFlag = true;
                   
            }
            else if(sArray[i] >= '0' && sArray[i] <= '9') numFlag = true;
            else return false;
        }
        return true;
        
    }
}

 

posted @ 2016-10-17 14:06  微微程序媛  阅读(195)  评论(0编辑  收藏  举报