Sunday, May 10, 2015

Valid Number

来源:Leetcode

原帖:http://oj.leetcode.com/problems/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.

代码:
 class Solution {  
 public:  
   // 20e5, 2., true; 5e, false  
   bool isNumber(const char* s) {  
     int length = strlen(s);  
     int i = 0, j = length - 1;  
     //case 1: space  
     while (i <= j && s[i] == ' ') i++;  
     while (i <= j && s[j] == ' ') j--;  
     //case 2: '+' or '-'  
     if (i <= j && s[i] == '+' || s[i] == '-') i++;  
     if (i > j) return false;  
     bool num = false, dot = false, exp = false;  
     while (i <= j) {  
       if (isdigit(s[i])) {  
         num = true;  
       } else if (s[i] == '.') { // .., e.   
         if (dot || exp) return false; // '.' 'e'  
         dot = true;  
       } else if (s[i] == 'e') {  
         if (exp || !num) return false; // e5 -> false; 1.e2 -> ture; 1.e -> false  
         exp = true;  
         num = false;  
       } else if (s[i] == '+' || s[i] == '-') {  
         if (s[i-1] != 'e') return false;  
       } else {  
         return false;  
       }  
       i++;  
     }  
     return num;  
   }  
 };  

No comments:

Post a Comment