首页 > 其他 > 详细

LeetCode | Valid Number

时间:2014-03-14 18:25:38      阅读:470      评论:0      收藏:0      [点我收藏+]

题目

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:利用正则表达式。

解法2:直接利用java提供的parseDouble或parseFloat函数帮助判断,这算是投机取巧的方法了,需要注意的是java类库里认为以“f”, "F", "d", "D"结尾的都是合法的,而LeetCode上都视为非法,需要特殊处理下。parseDouble和parseFloat具体的实现方法都是用的类库中的FloatingDecimal.readJavaFormatString(s),源码参见http://www.bvbcode.com/cn/joa60xtr-137004。

解法1

public class ValidNumber {
	public boolean isNumber(String s) {
		return s.trim().matches("[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?");
	}
}
解法2

public class ValidNumber {
	public boolean isNumber(String s) {
		if (s.contains("f") || s.contains("f") || s.contains("d")
				|| s.contains("D")) {
			return false;
		}
		try {
			Double.parseDouble(s);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
}

LeetCode | Valid Number,布布扣,bubuko.com

LeetCode | Valid Number

原文:http://blog.csdn.net/perfect8886/article/details/21186623

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!