LeetCode65 Valid Number 解题报告
2018-01-11 20:35
441 查看
Validate if a given string is numeric.
Some examples:
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
题目的意思非常简单,就是给一个字符串,判断其输入是否为数字类型。
解题的时候必须要考虑输入的各种类型,给的例子还不够全面 例如
通过测试例子可以得到,同时‘.’跟‘e’都不能单独存在,且‘e’前后必须跟有数字,后面数字必须为整数,即‘.’必须在‘e’的前面
同时 ‘.’后面必须接整数,下面的解法比较简单,比较容易出错,暂时也没有想到比较好的方法。通过两个bool变量来保证‘.’和‘e’的有效性(即只出现一次)。
Some examples:
"0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
题目的意思非常简单,就是给一个字符串,判断其输入是否为数字类型。
解题的时候必须要考虑输入的各种类型,给的例子还不够全面 例如
string s1="6e+"; //f string s2=".e1"; //f string s3="1.e2"; //t string s4="4.4e+4.2"; //f string s4=".e"; //f
通过测试例子可以得到,同时‘.’跟‘e’都不能单独存在,且‘e’前后必须跟有数字,后面数字必须为整数,即‘.’必须在‘e’的前面
同时 ‘.’后面必须接整数,下面的解法比较简单,比较容易出错,暂时也没有想到比较好的方法。通过两个bool变量来保证‘.’和‘e’的有效性(即只出现一次)。
bool isNumber(string s) { if(s.size()==0) { return false; } //去掉前面的空格 int start=0; for(;s[start]==' ';start++) {} //去掉后面的空格 int len=s.size()-1; if(start==s.size()) { return false; } for(;s[len]==' ';len--) {} if(s[start]=='-'||s[start]=='+') { start++; } int is_sci=false; int is_float=false; for(int i=start;i<=len;i++) { if(isDigit(s[i])) { } else if(s[i]=='.'&&is_float==false&&start!=len&&is_sci==false) { if(i>start&&isDigit(s[i-1])) { is_float=true; } else if(i<len&&isDigit(s[i+1])) { is_float=true; } else{ return false; } } else if(s[i]=='e'&&is_sci==false&&i!=len&&i!=start) { if(s[i+1]=='-'||s[i+1]=='+') { i++; if(i==len) { return false; } } is_sci=true; } else { return false; } } return true; }
相关文章推荐
- 【LeetCode】Valid Number 解题报告
- 【LeetCode】Permutations II 解题报告
- 【LeetCode】Rotate List 解题报告
- [Leetcode] 751. IP to CIDR 解题报告
- [Leetcode] 633. Sum of Square Numbers 解题报告
- LeetCode - 136. Single Number - ( C++ ) - 解题报告 - 位运算思路 xor
- [Leetcode] 476. Number Complement 解题报告
- [Leetcode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 解题报告
- LeetCode: Word Break II 解题报告
- [Leetcode] 145. Binary Tree Postorder Traversal 解题报告
- [Leetcode] 382. Linked List Random Node 解题报告
- LeetCode: Maximum Subarray 解题报告
- [leetcode] 53. Maximum Subarray 解题报告
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- Leetcode 72. Edit Distance 编辑距离 解题报告
- [LeetCode]Word Break,解题报告
- [leetcode] 82. Remove Duplicates from Sorted List II 解题报告
- LeetCode - 413. Arithmetic Slices - 含中文题意解释 - O(n) - ( C++ ) - 解题报告
- 【LeetCode】298.Binary Tree Longest Consecutive Sequence(Medium)(加锁题)解题报告
- Leetcode 401. Binary Watch 二进制的表 解题报告