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.
思路
There is no complex algorithem, just checking each char from input String
代码
// {前缀空格}{浮点数}{e}{正数}{后缀空格}
class Solution {
public boolean isNumber(String s) {
int len = s.length();
int i = 0;
int right = len - 1; // delete white spaces on both sides
while (i <= right && Character.isWhitespace(s.charAt(i))) i++;
if (i > len - 1) return false;
while (i <= right && Character.isWhitespace(s.charAt(right))) right--; // check +/- sign
if (s.charAt(i) == '+' || s.charAt(i) == '-') i++; boolean num = false; // is a digit
boolean dot = false; // is a '.'
boolean exp = false; // is a 'e' while (i <= right) {
char c = s.charAt(i);
// first char should be digit
if (Character.isDigit(c)) {
num = true;
}
else if (c == '.') {
// exp and dot cannot before '.'
if(exp || dot) return false;
dot = true;
}
else if (c == 'e') {
// only one 'e'can exist
// 'e' should after num
if(exp || num == false) return false;
exp = true;
// after 'e' should exist num, so set num as default false
num = false;
}
else if (c == '+' || c == '-') {
if (s.charAt(i - 1) != 'e') return false;
}
else {
return false;
}
i++;
}
return num;
}
}
变种之简化版本的Valid Number : checking +/- numbers including decimal numbers
需要跟面试官confirm
以下哪些算valid,若以下test case中,蓝色字体是valid的
123
-123
123.123
-123.123
.123
-.123
123.
123-.
那么:
1. Decimal point 前面必须是数字
2. Decimal point 后面必须是数字
3. 整个valid number最后是以数字结尾
public boolean isNumber(String s) {
int len = s.length();
int i = 0;
int right = len - 1; // delete white spaces on both sides
while (i <= right && Character.isWhitespace(s.charAt(i))) i++;
if (i > len - 1) return false;
while (i <= right && Character.isWhitespace(s.charAt(right))) right--; // check +/- sign
if (s.charAt(i) == '+' || s.charAt(i) == '-') i++; boolean num = false; // is a digit
boolean dot = false; // is a '.' while (i <= right) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = true;
}
else if (c == '.') {
// (1) .. two dots (2) no number before dot (3) - before dot
if( dot || num == false || s.charAt(i-1) == '-') return false;
dot = true;
// check whether there is number after decimal point
num = false;
}
else {
return false;
}
i++;
}
return num;
}