Given a string, return whether it represents a number. Here are the different kinds of numbers:
- "10", a positive integer
- "-10", a negative integer
- "10.1", a positive real number
- "-10.1", a negative real number
- "1e5", a number in scientific notation
And here are examples of non-numbers:
- "a"
- "x 1"
- "a -2"
- "-"
Example:
Input: str = "10"
Output: true
Approach
C++
#include <bits/stdc++.h>using namespace std;//function to check if the number//represented by string is valid or notbool isValidNumber(string s){int n = s.size();int digit = 0, dots = 0;int i = 0;//iterate till their is spaces//in start of numberwhile (i < n && s[i] == ' ')i++;//if positive sign or negaitve signif (s[i] == '+' || s[i] == '-')i++;while (i < n){if (isdigit(s[i])){digit++;i++;}else if (s[i] == '.'){dots++;i++;}elsebreak;}//if their is no digits and// and we have dots then return falseif (digit == 0 || dots > 1)return false;//if thier is exponentif (s[i] == 'e'){i++;//if + ,- signif (s[i] == '+' || s[i] == '-')i++;digit = 0;while (i < n){if (isdigit(s[i])){i++;digit++;}elsebreak;}//if no digits retunr falseif (digit == 0)return false;}//if spaces move to nextwhile (i < n && s[i] == ' ')i++;//if we not reach at end the return falseif (i < n)return false;//else number is validreturn true;}int main(){string s = "10";if (isValidNumber(s))cout << "true\n";elsecout << "false\n";return 0;}
No comments:
Post a Comment