主要问题:
判断输入的字符串是否一个合法数字
思路:
垃圾题目,不说清楚格式。。只能靠试(小数点前后有没有数字真的恶心)
思路就是有限状态机,下面是我自己摸索出来的图,按着这个来打代码就行了。
代码:
1 class Solution { 2 public: 3 bool isNumber(string s) { 4 int state = 0; 5 while(s[0]==‘ ‘) s.erase(0,1); //删除前面的空格 6 while(s[s.length()-1]==‘ ‘) s.erase(s.length()-1, 1); //删除最后的空格 7 for (int i = 0; i < s.length(); i++) { 8 char c = s[i]; 9 if (state == 0) { 10 if (c == ‘+‘ || c == ‘-‘) state = 1; 11 else if (c >= ‘0‘ && c <= ‘9‘) state = 2; 12 else if (c == ‘.‘) state = 3; 13 else return false; 14 } 15 else if (state == 1) { 16 if (c >= ‘0‘ && c <= ‘9‘) state = 2; 17 else if (c == ‘.‘) state = 3; 18 else return false; 19 } 20 else if (state == 2) { 21 if (c >= ‘0‘ && c <= ‘9‘) state = 2; 22 else if (c == ‘.‘) state = 4; 23 else if (c == ‘e‘) state = 5; 24 else return false; 25 } 26 else if (state == 3) { 27 if (c >= ‘0‘ && c <= ‘9‘) state = 4; 28 else return false; 29 } 30 else if (state == 4) { 31 if (c >= ‘0‘ && c <= ‘9‘) state = 4; 32 else if (c == ‘e‘) state = 5; 33 else return false; 34 } 35 else if (state == 5) { 36 if (c == ‘+‘ || c == ‘-‘) state = 6; 37 else if (c >= ‘0‘ && c <= ‘9‘) state = 7; 38 else return false; 39 } 40 else if (state == 6) { 41 if (c >= ‘0‘ && c <= ‘9‘) state = 7; 42 else return false; 43 } 44 else if (state == 7) { 45 if (c >= ‘0‘ && c <= ‘9‘) state = 7; 46 else return false; 47 } 48 } 49 return (state == 2 || state == 4 || state == 7); 50 } 51 };
原文:https://www.cnblogs.com/leo-lzj/p/10463497.html