Valid Number:from LeetCode
2014-05-15 10:29
387 查看
题目大意是:给出一个字符串,判断是否为合法的数字
输入比较多样比如
".3" "2e12" "-2.2e-1" “ 2.2 ” 等等都是合法的,难点在于情况多比较复杂。
这里给出一个我的解法,网上也流传了类似的解法,用的都是bool开关(我起得名字呵呵)
看代码前还是说说思想吧。我们要判断的是非法情况,比方e不能出现两次,所以如果当前字符是e 所以如果已经有e了即 hase为真 则返回false。而e隔断了两个数字的关系,所以如果当前是e并且合法则 hasdot等都是前面的数字的情况了,所以现在算是没有小数点(但题目样例看了e后面的数不能有小数点,呵呵),等等情况啦。。。
输入比较多样比如
".3" "2e12" "-2.2e-1" “ 2.2 ” 等等都是合法的,难点在于情况多比较复杂。
这里给出一个我的解法,网上也流传了类似的解法,用的都是bool开关(我起得名字呵呵)
看代码前还是说说思想吧。我们要判断的是非法情况,比方e不能出现两次,所以如果当前字符是e 所以如果已经有e了即 hase为真 则返回false。而e隔断了两个数字的关系,所以如果当前是e并且合法则 hasdot等都是前面的数字的情况了,所以现在算是没有小数点(但题目样例看了e后面的数不能有小数点,呵呵),等等情况啦。。。
class Solution { public: bool isNumber(const char *s) { int begin=0; int end=strlen(s)-1; while(end>=0 &&(s[end]==' '||s[end]==' '))end--; while(s[begin]==' ' || s[begin]==' ')begin++; if(s[begin]=='\0')return false; bool hasnum=false,hasdot=false,hase=false,hassig=false; while(begin<=end) { if(isdigit(s[begin])) { hasnum=true; }else if(s[begin]=='.') { if(hasdot || hase) return false; hasdot=true; }else if(s[begin]=='e'){ if(hase || !hasnum)return false; hase=true; hasnum=false; hassig=false; hasdot=false; }else if(s[begin]=='+' || s[begin]=='-') { if(hasnum || hassig || hasdot)return false; hassig=true; }else { return false; }; begin++; } if((hasdot||hase||hassig) && !hasnum)return false; return true; } };
相关文章推荐
- Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 26. Remove Duplicates from Sorted Array
- [Leetcode] 19. Remove Nth Node From End of List
- 【LeetCode从零单排】No83 Remove Duplicates from Sorted List
- 面试题15:链表中倒数第k个节点(Leetcode-19:Remove Nth Node From End of List)
- Leetcode - Tree - 106. Construct Binary Tree from Inorder and Postorder Traversal(根据中序遍历和后序遍历重构二叉树)
- LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode:Remove Duplicates from Sorted Array II
- Leetcode -- Remove Duplicates from Sorted Array
- leetcode 日经贴,Cpp code -Remove Duplicates from Sorted List II
- [LeetCode]65 Valid Number
- LeetCode: Remove Duplicates from Sorted List II
- [LeetCode]83 Remove Duplicates from Sorted List
- 【LeetCode-19】Remove Nth Node From End of List(C++)
- [LeetCode][Java] Remove Duplicates from Sorted Array II
- LeetCode题解:Remove Duplicates from Sorted Array
- 【Leetcode】Remove Duplicates from Sorted Array
- leetcode: Remove Nth Node From End of List
- leetcode - Remove Nth Node From End of List
- LeetCode-106:Construct Binary Tree from Inorder and Postorder Traversal (利用中序和后序遍历构建二叉树) -- medium