題目鏈接:表示數值的字符串
題意:
請實現一個函數用來判斷字符串是否表示數值(包括整數和小數)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示數值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是
解題思路:
- 對字符串中的每個字符進行判斷分析
- e(E)後面只能接數字,並且不能出現2次
- 對於+、-號,只能出現在第一個字符或者是e的後一位
- 對於小數點,不能出現2次,e後面不能出現小數點
class Solution {
public:
bool isNumeric(char* string){
int spot = 0, hasE = 0; // 判斷點和E的個數
int len = strlen(string);
bool res = true;
for(int i = 0; i < len; i++){
char c = string[i];
if(c == 'e' || c == 'E'){
if(i == len - 1 || i == 0 || hasE == 1){ // 如果E的個數大於1
res = false;
}
hasE = 1;
}
else if(c == '.'){ // 如果點的個數大於1
if(hasE || spot){
res = false;
}
spot = 1;
}
else if(c == '+' || c == '-'){ // 如果中間出現正負號前需要有E
if(i > 0 && string[i-1] != 'e' && string[i-1] != 'E'){
res = false;
}
}
else if(c < '0' || c > '9'){ // 放在最後判斷,否則E和.就會報錯
res = false;
}
}
return res;
}
};