DIY: Valid Number
Solve the interview question "Valid Number" in this lesson.
We'll cover the following
Problem statement
Validate if a given string can be interpreted as a decimal number or not. Here is a list of characters that can appear in a valid decimal number:
-
Numbers -
0-9
-
Exponent -
"e"
-
Positive/negative sign -
"+"/"-"
-
Decimal point -
"."
The context of these characters also matters in the input. Here are some examples:
"0"
=> true
" 0.1 "
=> true
".55"
=> true
"abc"
=> false
"1 a"
=> false
" -90e3 "
=> true
" 1e"
=> false
"e3"
=> false
" 6e-1"
=> true
" 99e2.5 "
=> false
" --6 "
=> false
Input
The input will be a string, s. The following is an example input:
s = "53.5e93"
Output
The output will be a Boolean value that represents whether the number is valid or not. For the above input, the output will be:
True
Coding exercise
For this coding exercise, you need to implement the is_number_valid(s)
function, where s
is the input string. The function should return a Boolean that shows whether the number is valid or not.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.