本文主要是介绍【剑指offer】表示数值的字符串(字符串),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
链接
https://www.nowcoder.com/practice/6f8c901d091949a5837e24bb82a731f2?tpId=13&tqId=11206&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
代码
class Solution {
public:bool isNumeric(char* string){if(string == NULL){return false;}char *first = NULL, *second = NULL;int flagE = -1;for(int i = 0; i < strlen(string); i++){if(string[i] == 'e' || string[i] == 'E'){flagE = i;}}if(flagE == -1){return isNum(string);}else{first = (char*)malloc(sizeof(char) * (flagE + 1));second = (char*)malloc(sizeof(char) *(strlen(string) - flagE));int i, j;for(i = 0; i < flagE; i++){first[i] = string[i];}first[i] = '\0';for(i = 0, j = flagE+1; j < strlen(string); i++, j++){second[i] = string[j];}second[i] = '\0';return isNum(first) && isInt(second);}}bool isNum(char* string){if(string == NULL){return false;}bool flag = true;if(!(string[0] == '-' || string[0] == '+' || (string[0] > '0' && string[0] <= '9'))){flag = false;}bool xiaoshudian = false; // 表示是否已经有小数点for(int i = 1; i < strlen(string); i++){if(string[i] == '.' && string[i+1] == '\0'){flag = false;break;}else if(string[i] == '.' && xiaoshudian == false){xiaoshudian = true;}else if(string[i] == '.' && xiaoshudian == true){flag = false;break;}else if(string[i] >= '0' && string[i] <= '9'){continue;}else{flag = false;break;}if(string[i+1] == '\0'){break;}}return flag;}bool isInt(char* string){if(string == NULL){return false;}bool flag = true;if(!(string[0] == '-' || string[0] == '+' || (string[0] > '0' && string[0] <= '9'))){flag = false;}for(int i = 1; i < strlen(string); i++){if(string[i] >= '0' && string[i] <= '9'){continue;}else{flag = false;break;}if(string[i+1] == '\0'){break;}}return flag;}
};
这篇关于【剑指offer】表示数值的字符串(字符串)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!