LeetCode OJ 之 Valid Number (有效数字的判断)
来源:互联网 发布:熊猫安卓手游直播软件 编辑:程序博客网 时间:2024/05/18 01:34
题目:
Validate if a given string is numeric.
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.
判断给的字符串是否是一个数字。注意:题目的说明是模棱两可的,你应该考虑到所有可能。
思路:
1、对于空格,只能出现在开始和结尾,如" 123 "。出现在中间则不符合条件,”123 123“。
2、对于+-,只能出现在非空格的首位和e或者E的下一位。比如“ +123” , “123E-10”,最多出现两次。
3、对于. ,可以出现在数字前和数字后,如 ".123",或者”123.“,但是不能出现在e和E后,比如”123E5.“,最多出现一次。
4、对于e和E,只能出现在数字后面,比如”123E0“,并且后面必须跟”+“或者”-“或者数字,而且后面不能再有”.",并且最多只能出现一次。
代码:
class Solution {public: bool isNumber(const char *s) { bool has_dot = false; bool has_e = false; bool has_num = false; while(*s == ' ') //前面都是空格 s++; if(*s == '+' || *s == '-') //首位是+- s++; while(*s && *s != ' ') //*s是' '时也停止遍历,如"123 123","123 " { if((*s == 'e' || *s == 'E') && !has_e) //遇到E或者e,并且没有出现过e,就继续判断 { if(!has_num) //e前面必须有数字,比如e12是非法的数 return false; has_dot = has_e = true;//如果出现e,则has_dot也要置为真,因为e后面也不能有'.' if(*(s+1) == '-' || *(s+1) == '+') //下一位可以为符号位 '+-' { s++; } if (!isdigit(*(s + 1))) //下一位或者符号位的下一位必须为数字,0也可以 return false; } else { if(*s == '.' && !has_dot) //'.'之前不能有e,有e的时候已经把has_dot置为真 { has_dot = true; } else { if(isdigit(*s)) { has_num = true; } else return false;//如果上面情况都不满足,则返回假 } } s++; } while(*s) //判断空格后面是否还有其他字符,如果有,则非法,如"123 123" { if(*s == ' ') s++; else return false; } return has_num;//如果没有数字也返回假,如'.' }};
0 0
- LeetCode OJ 之 Valid Number (有效数字的判断)
- LeetCode OJ 之 Valid Parentheses(有效的括号判断)
- 【LeetCode】- Valid Number(有效数字)
- [LeetCode]Valid Number有效数字
- Valid Number 判断一个数字是否有效
- leetCode 65.Valid Number (有效数字)
- LeetCode OJ 之 Longest Valid Parentheses (最长有效括号)
- LeetCode OJ 之 Single Number (唯一的数字)
- LeetCode OJ 之 Largest Number (最大的数字)
- LeetCode OJ 之 Missing Number (丢失的数字)
- LeetCode OJ:Valid Number
- LeetCode OJ - Valid Number
- LeetCode OJ Valid Number
- [LeetCode OJ]Valid Number
- [Lintcode]Valid Number有效数字
- LeetCode OJ 之 Valid Sudoku (数独判断)
- LeetCode 65. Valid Number(校验数字)
- LeetCode OJ 之 Palindrome Number(回文数字)
- MySQL 5.6.14 win32 zip版安装
- 黑马程序员_面向对象(3)
- dede让channelartlist标签支持currentstyle属性 完美解决
- jdk1.5高新技术(四) 类加载器
- 多个UpdatePanel控件相互引发刷新的使用
- LeetCode OJ 之 Valid Number (有效数字的判断)
- C++11 lambda 表达式解析
- tomcat配置与myeclipse激活遇到的两个问题
- Objective-C 基础
- android 小问题积累中
- 钽电解电容跟铝电解电容的区别
- iOS-实现最简单的画线功能 . 转
- Python Selenium 学习笔记(三)键盘和鼠标操作
- IOS Quartz 各种绘制图形用法---实现画图片、写文字、画线、椭圆、矩形、棱形等