leetcode - Valid Number
2013-11-20 15:54 张汉生 阅读(195) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 bool isInt(const char * s, int start, int end){ 4 if (end < start) 5 return false; 6 if (start<=end && (s[start] == '+' || s[start] == '-')) 7 start++; 8 if (end<start) 9 return false; 10 for (int i = start; i <= end; i++){ 11 if (s[i]<'0' || s[i]>'9') 12 return false; 13 } 14 return true; 15 } 16 bool isDouble(const char * s, int start, int end){ 17 if (start <= end && (s[start] == '+' || s[start] == '-')) 18 start++; 19 for (int i = start; i <= end; i++){ 20 if (s[i] == '.'){ 21 if (i + 1 <= end && (s[i + 1] == '-' || s[i + 1] == '+')) 22 return false; 23 if (i == start) 24 return isInt(s, i + 1, end); 25 else if (i == end) 26 return isInt(s, start, i-1); 27 else return isInt(s, start, i - 1) && isInt(s, i + 1, end); 28 } 29 } 30 return isInt(s, start, end); 31 } 32 bool isNumber(const char *s) { 33 // Note: The Solution object is instantiated only once and is reused by each test case. 34 int len = strlen(s); 35 int start = 0, end = len - 1; 36 while (start <= end && (s[start] == ' ')) 37 start++; 38 while (end >= start && s[end] == ' ') 39 end--; 40 for (int i = start; i <= end; i++){ 41 if (s[i] == 'e' || s[i] == 'E'){ 42 return isDouble(s, start, i - 1) && isInt(s, i + 1, end); 43 } 44 } 45 return isDouble(s, start , end); 46 } 47 };