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: Checks
- Numbers 0-9
- Exponent - "e"
- Positive/negative sign - "+"/"-"
- Decimal point - "."
Example 1:
Input: s = "3" Output: true
Approach:
Java
public class ValidNumber {
public static void main(String[] args) {
String s = "0e";
System.out.println(isNumber(s));
}
// method to check if the number
// represented by string is valid or not
private static boolean isNumber(String s) {
int n = s.length();
int digit = 0, dots = 0;
int i = 0;
// iterate till their is spaces
// in start of number
while (i < n && s.charAt(i) == ' ')
i++;
// if positive sign or negative sign
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-'))
i++;
while (i < n) {
if (Character.isDigit(s.charAt(i))) {
digit++;
i++;
} else if (s.charAt(i) == '.') {
dots++;
i++;
} else
break;
}
// if their is no digits and
// and we have dots then return false
if (digit == 0 || dots > 1)
return false;
// if their is exponent
if (i<n && s.charAt(i) == 'e') {
i++;
// if + ,- sign
if (i<n && (s.charAt(i) == '+' || s.charAt(i) == '-'))
i++;
digit = 0;
while (i < n) {
if (Character.isDigit(s.charAt(i))) {
i++;
digit++;
} else
break;
}
// if no digits return false
if (digit == 0)
return false;
}
// if spaces move to next
while (i < n && s.charAt(i) == ' ')
i++;
// if we not reach at end the return false
if (i < n)
return false;
// else number is valid
return true;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to check if the number
//represented by string is valid or not
bool isNumber(string s)
{
int n=s.size();
int digit=0,dots=0;
int i=0;
//iterate till their is spaces
//in start of number
while(i<n&&s[i]==' ')
i++;
//if positive sign or negaitve sign
if(s[i]=='+'||s[i]=='-')
i++;
while(i<n)
{
if(isdigit(s[i]))
{
digit++;
i++;
}
else if(s[i]=='.')
{
dots++;
i++;
}
else
break;
}
//if their is no digits and
// and we have dots then return false
if(digit==0||dots>1)
return false;
//if thier is exponent
if(s[i]=='e')
{
i++;
//if + ,- sign
if(s[i]=='+'||s[i]=='-')
i++;
digit=0;
while(i<n)
{
if(isdigit(s[i]))
{
i++;
digit++;
}
else
break;
}
//if no digits retunr false
if(digit==0)
return false;
}
//if spaces move to next
while(i<n&&s[i]==' ')
i++;
//if we not reach at end the return false
if(i<n)
return false;
//else number is valid
return true;
}
int main()
{
string s="3";
if(isNumber(s))
cout<<"true\n";
else
cout<<"false\n";
return 0;
}
No comments:
Post a Comment