【LeetCode】- Valid Number(有效数字)
2014-08-27 15:08
344 查看
[ 问题: ]
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.
[ 解法: ]
注意:s不能以'f'或'd'结尾, 因为如果以它们结尾时,使用Double转换不会报错,
但是类似:10.1f, 20.1d 按照题意并不能算作有效数值,所以我们不能放过这些“漏网之鱼”。
[ 拓展: ]
1.float:单精度浮点数
声明为float类型的浮点数时,要在结尾加F或f。
float f1 = 11.11F; // 正的浮点数
float f2 = -17.15f; // 负的浮点数
2.double:双精度浮点数
声明为double类型的浮点数时,可在结尾加D或d。当然也可不加,因为浮点类型默认的类型是double。
double d1 = 11.11223D; // 正的浮点数
double d2 = 11.11333d; // 正的浮点数
double d3 = -17.15555; // 负的浮点数
** 这里建议在double数据类型的数后面加上D或d,以便能够和单精度浮点数区分。
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.
[ 解法: ]
public class Solution { public static boolean isNumber(String s) { try { s = s.toLowerCase(); Double.parseDouble(s); } catch (Exception e) { return false; } return s.charAt(s.length() -1) != 'f' && s.charAt(s.length() - 1) != 'd'; } }
注意:s不能以'f'或'd'结尾, 因为如果以它们结尾时,使用Double转换不会报错,
但是类似:10.1f, 20.1d 按照题意并不能算作有效数值,所以我们不能放过这些“漏网之鱼”。
[ 拓展: ]
1.float:单精度浮点数
声明为float类型的浮点数时,要在结尾加F或f。
float f1 = 11.11F; // 正的浮点数
float f2 = -17.15f; // 负的浮点数
2.double:双精度浮点数
声明为double类型的浮点数时,可在结尾加D或d。当然也可不加,因为浮点类型默认的类型是double。
double d1 = 11.11223D; // 正的浮点数
double d2 = 11.11333d; // 正的浮点数
double d3 = -17.15555; // 负的浮点数
** 这里建议在double数据类型的数后面加上D或d,以便能够和单精度浮点数区分。
相关文章推荐
- LeetCode OJ 之 Valid Number (有效数字的判断)
- LeetCode-Valid Number-合法数字-状态机
- valid number 判断字符串是否为有效数字
- Leet Code 65 Valid Number - 有效的数字 - Java
- leetCode 65.Valid Number (有效数字)
- leetCode 65.Valid Number (有效数字)
- LeetCode65——Valid Number(使用DFA)来判断字符串是否为数字
- LeetCode Valid Number 有效数字(有限自动机)
- [Leetcode] valid number 验证数字
- Valid Number 判断一个数字是否有效
- 每日一题 LeetCode 有效的数字 Python实现
- [LeetCode] Valid Number 验证数字
- Valid Number 判断一个string是不是有效地数字表达式 @LeetCode
- leetcode-65-有效的数字
- Leetcode: Valid Number
- Leetcode: Valid Number
- LeetCode : 12 整数转罗马数字 C++
- Leetcode刷题记——18. 4Sum(4个数字和)
- LeetCode学习(2) 将罗马数字转换为数字
- LeetCode( Valid Parentheses)有效的括号