# Valid Number

Validate if a given string is numeric.

Examples:

• "0" => true
• " 0.1 " => true
• "abc" => false
• "1 a" => false
• "2e10" => true
Return 0 / 1 ( 0 for false, 1 for true ) for this problem

Clarify the question using “See Expected Output”

• Is 1u ( which may be a representation for unsigned integers valid?
For this problem, no.
• Is 0.1e10 valid?
Yes
• -01.1e-10?
Yes
Not for the purpose of this problem
• 3. (. not followed by a digit)?
No
• Can exponent have decimal numbers? 3e0.1?
Not for this problem.
• Is 1f ( floating point number with f as prefix ) valid?
Not for this problem.
• How about 1000LL or 1000L ( C++ representation for long and long long numbers )?
Not for this problem.
• How about integers preceded by 00 or 0? like 008?
Yes for this problem
Solution:

Time: O(n)
Space: O(1)

public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
public int isNumber(final String A) {
char[] arr = A.toCharArray();
int i = 0;
boolean first = true;
boolean second = false;
boolean dot = false;
boolean needsNumber = false;
boolean e = false;
boolean number = false;
while (i < arr.length) {
char c = arr[i];
if (Character.isDigit(c)) {
number = true;
needsNumber = false;
i ++;
continue;
} else if (needsNumber) {
return 0;
} else if (c == '-' || c == '+') {
if (first) {
first = false;
} else if (e && !second) {
second = true;
} else {
return 0;
}
} else if (c == ' ') {
if (number) {
while (i < arr.length) {
if (arr[i] != ' ') {
return 0;
}
i ++;
}
}
} else if (c == '.') {
if (dot || e) {
return 0;
} else {
dot = true;
number = false;
needsNumber = true;
}
} else if (c == 'e') {
if (e) {
return 0;
} else {
e = true;
number = false;
}
} else {
return 0;
}
i ++;
}
return number ? 1 : 0;
}
}