题解 | #表示数值的字符串# 逻辑判断带注释
表示数值的字符串
https://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8
#include <clocale> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return bool布尔型 */ bool isNumeric(string str) { // write code here int n = str.size(); int loction = 0, nums = 0; bool has1 = false, has2 = false, has3 = false, has4 = false; // 排除若干空格 while(loction<n && str[loction] == ' '){ loction++; } // 整数逻辑 if(loction<n && (str[loction] == '+' || str[loction] == '-')){ has1 = true; loction++; } while(loction<n && str[loction] <= '9' && str[loction] >= '0'){ nums++; loction++; } // 小数逻辑(主要处理小数点对应的情况) if(loction<n && str[loction] == '.'){ has2 = true; loction++; while(loction<n && str[loction] <= '9' && str[loction] >= '0'){ nums++; loction++; } } int nums1 = nums; // 科学计数法逻辑 if(loction<n && (str[loction] == 'e' || str[loction] == 'E')){ has3 = true; loction++; if(loction<n && (str[loction] == '+' || str[loction] == '-')){ has4 = true; loction++; } while(loction<n && str[loction] <= '9' && str[loction] >= '0'){ nums++; loction++; } } while(loction<n && str[loction] == ' '){ loction++; } // 对于正确返回值的判断 if(loction ==n && nums >0 && has2 == false && has3 ==false && has4 == false){ // 整数判断 cout << "int" << endl; return true; }else if(loction ==n && nums >0 && has2 == true && has3 == false && has4 == false){ // 小数逻辑 cout << "point" << endl; return true; } else if(loction ==n && nums1 >0 && nums > nums1 && has3 == true){ // 科学计数法逻辑 cout << "science" << endl; return true; } return false; } };
本题目的逻辑是可以理解的,但是难以统一应用的,除此之外没有什么说法,把要实现的逻辑拆成小部分分别实现,然后根据错误反馈调整就好。