Leetcode刷题笔记 剑指 Offer 20. 表示数值的字符串

tech2022-08-01  135

剑指 Offer 20. 表示数值的字符串

时间:2020年9月2日 知识点:字符串 题目链接: https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/

题目 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、"-1E-16"、“0123"都表示数值,但"12e”、“1a3.14”、“1.2.3”、"±5"及"12e+5.4"都不是。

代码

#include <stdio.h> #include <cstring> #include <iostream> using namespace std; class Solution { public: bool isNumber(string s) { int op=0; //+、- int num=0; //数字 int e=0; //E、e int d=0; //. int n= s.size();//总个数 int i=0; //下标 while(i < n && s[i]==' ')i++; while(i < n){ if('0'<=s[i]&&s[i]<='9') num = 1; else if(s[i]== 'e' || s[i]=='E'){ //之前过出现E、e 或者 E、e前面没有数字 不是数值 if(e || num==0) return false; e = 1; op=0;d=0;num=0;//前面有的符号、点、数字都不考虑 } else if(s[i]=='+' || s[i]=='-'){ //之前有 符号、数字、点 不是数值 if(op || num || d) return false; op = 1; } else if(s[i] == '.'){ //之前有 点、E、e 不是数值 if(d || e) return false; d = 1; }else if(s[i]==' '){ //有空格 直接退出 特判 '1 ' break; } else { return false; } i++; } while(i < n && s[i]==' ')i++; return i==n && num; //特判 '1.2E' E后面要有数字 } }; int main() { string str="1 "; Solution s; cout<<s.isNumber(str); return 0; }

今天也是爱zz的一天哦!

最新回复(0)