Validate if a given string can be interpreted as a decimal number.
Some examples:
"0"
=>true
" 0.1 "
=>true
"abc"
=>false
"1 a"
=>false
"2e10"
=>true
" -90e3 "
=>true
" 1e"
=>false
"e3"
=>false
" 6e-1"
=>true
" 99e2.5 "
=>false
"53.5e93"
=>true
" --6 "
=>false
"-+3"
=>false
"95a54e53"
=>false
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:
- Numbers 0-9
- Exponent - "e"
- Positive/negative sign - "+"/"-"
- Decimal point - "."
Of course, the context of these characters also matters in the input.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
有效数字。剑指Offer里有一道一模一样的题。唯一多的case是对数函数底数e是有大小写的。
题意是给你一个input字符串,请你判断他是否为有效数字。题目没有给出非常具体的有效数字的定义,但是给了一些例子帮你理解什么叫有效什么叫无效。
思路只能是从例子下手了。注意到这么几点
- 首先input字符串里面一定需要有数字
- 之后需要判断是否有e,如果有e,则必须先看到数字才行,否则就是错的
- 如果碰到小数点,但是是在e之后或者已经出现过小数点了,就是错的
- 如果遇到加减号,看一下是不是在input的首位或者在不在e之后的那一位上,如果不满足则是错的
- 最后判断有没有遇到数字
照着这个思路,代码就不难写了。但是有的case,讨论区很多同学都不认同,我也在这里分享出来。
test(1, "123", true);test(2, " 123 ", true);test(3, "0", true);test(4, "0123", true); //Cannot agreetest(5, "00", true); //Cannot agreetest(6, "-10", true);test(7, "-0", true);test(8, "123.5", true);test(9, "123.000000", true);test(10, "-500.777", true);test(11, "0.0000001", true);test(12, "0.00000", true);test(13, "0.", true); //Cannot be more disagree!!!test(14, "00.5", true); //Strongly cannot agreetest(15, "123e1", true);test(16, "1.23e10", true);test(17, "0.5e-10", true);test(18, "1.0e4.5", false);test(19, "0.5e04", true);test(20, "12 3", false);test(21, "1a3", false);test(22, "", false);test(23, " ", false);test(24, null, false);test(25, ".1", true); //Ok, if you say sotest(26, ".", false);test(27, "2e0", true); //Really?!test(28, "+.8", true);test(29, " 005047e+6", true); //Damn = =|||
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public boolean isNumber(String s) { 3 boolean eSeen = false; 4 boolean numSeen = false; 5 boolean dotSeen = false; 6 s = s.trim(); 7 for (int i = 0; i < s.length(); i++) { 8 char c = s.charAt(i); 9 if (Character.isDigit(c)) { 10 numSeen = true; 11 } else if (c == 'e' || c == 'E') { 12 if (eSeen || !numSeen) { 13 return false; 14 } 15 eSeen = true; 16 numSeen = false; 17 } else if (c == '.') { 18 if (eSeen || dotSeen) { 19 return false; 20 } 21 dotSeen = true; 22 } else if (c == '-' || c == '+') { 23 if (i != 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E') { 24 return false; 25 } 26 } else { 27 return false; 28 } 29 } 30 return numSeen; 31 } 32 }