LeetCode -- 65. Valid Number

 

直接抄答案:

1.Skip leading spaces.
2.Skip sign bit.
3.Integer, decimal point and fractional parts (make sure at least one digit exists)
4.Exponential bit. (There may be sign bits again and make sure there is digit following)
5.Skip following spaces.
6.Make sure that's the end.
bool isNumber(string s)
 {
     int n = s.size();
     if(n == 0) return false;
     
     int i = 0;
     //Skip leading spaces.
     while(s[i] == ' ') i++;
     
     //Significand
     if(s[i] == '+' || s[i] == '-') i++;
     
     int cnt = 0;
     //Integer part
     while(isdigit(s[i]))
     {
         i++;
         cnt++;
     }
     //Decimal point
     if(s[i] == '.') i++;
     //Fractional part
     while(isdigit(s[i]))
     {
         i++;
         cnt++;
     }
     if(cnt == 0) return false;  //No number in front or behind '.'
     
     //Exponential
     if(s[i] == 'e')
     {
         i++;
         if(s[i] == '+' || s[i] == '-') i++;
         if(!isdigit(s[i])) return false;    //No number follows
         while(isdigit(s[i])) i++;
     }
     
     //Skip following spaces;
     while(s[i] == ' ') i++;
     
     return s[i] == '\0';
 }

  

猜你喜欢

转载自www.cnblogs.com/feliz/p/11056921.html