Thursday, January 8, 2015

Valid Number (LeetCode Math)

Question: Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Idea: Let us have a look an example with all the possible elements:
"+566.758e+251"

The significant part "+566.758" should follow these rules:
1) the first symbol should be '+' or '-' or a digit.
2) contains at least a digit '0'->'9'
3) contains at most a dot '.'
4) should not contain other symbols, e.g. 'a', 'b', ' '(space).

The middle part 'e' should have either a single 'e' or reaches the end of the string.

The exponent part should follow these rules:
1) the first symbol should be '+', '-' or a digit.
1) should contain at least one digit
2) should not contain any other symbols.

So we use a pointer "i" to scan the trimmed string and check the three parts: (significant, middle and exponent) one by one. If there is any abnormal, return false; otherwise return true at the end of the program.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public boolean isNumber(String s) {  
     char[] c=s.trim().toCharArray();  
     if(c.length==0)  
       return false;  
     int i=0;  
     int numCounter=0;  
     int dotCounter=0;  
     if(isSymbol(c[i]))  
       i++;  
     for(;i<c.length;i++)  
     {  
       if(isNum(c[i]))  
       {  
         numCounter++;  
         continue;  
       }  
       if(c[i]=='.')  
       {  
         dotCounter++;  
         continue;  
       }  
       if(c[i]!='e')  
         return false;  
       else  
         break;  
     }  
     if(numCounter==0||dotCounter>1)  
       return false;  
     if(i==c.length)  
       return true;  
     else if(i<c.length&&c[i]!='e')  
       return false;  
     else  
       i++;  
     if(i<c.length&&isSymbol(c[i]))  
       i++;  
     numCounter=0;  
     for(;i<c.length;i++)  
     {  
       if(isNum(c[i]))  
       {  
         numCounter++;  
         continue;  
       }  
       return false;  
     }  
     if(numCounter<=0)  
       return false;  
     return true;  
   }  
   boolean isNum(char c)  
   {  
     return (c>='0'&&c<='9');  
   }  
   boolean isSymbol(char c)  
   {  
     return (c=='+'||c=='-');  
   }  
 }  

No comments:

Post a Comment