Valid Number
https://leetcode.com/problems/valid-number/description/
Thoughts
Code
/*
* @lc app=leetcode id=65 lang=cpp
*
* [65] Valid Number
*/
class Solution {
public:
bool isNumber(string s) {
const int N = s.size();
int i = 0;
// trim
while (i < N && s[i] == ' ') ++i;
// the sign
if (i < N && (s[i] == '+' || s[i] == '-')) ++i;
// digits until
bool digit = false;
while (i < N && (s[i] >= '0' && s[i] <= '9')) {
digit = true;
++i;
}
// the dot
if (i < N && s[i] == '.') ++i;
// continue
while (i < N && (s[i] >= '0' && s[i] <= '9')) {
digit = true;
++i;
}
// 'e'
if (i < N && s[i] == 'e' && digit) {
digit = false;
++i;
if (i < N && (s[i] == '+' || s[i] == '-')) ++i;
}
// continue
while (i < N && (s[i] >= '0' && s[i] <= '9')) {
digit = true;
++i;
}
// trim
while (i < N && s[i] == ' ') ++i;
return (i == N) && digit;
}
};
Analysis
Last updated