- Valid Number
Validate if a given string is numeric.
Example
Example 1:
Input: “0”
Output: true
Explanation: “0” can be converted to 0
Example 2:
Input: “0.1”
Output: true
Explanation: “0.1” can be converted to 0.1
Example 3:
Input: “abc”
Output: false
Example 4:
Input: “1 a”
Output: false
Example 5:
Input: “2e10”
Output: true
Explanation: “2e10” represents 20,000,000,000
解法1;
- 先去掉开头和结尾的空格,记下l和r。
- 从l到r循环,如果是数字跳过,记下.和e的位置。如果.和e出现多次,返回false。
- 最后判断.前后是不是数字。e不能出现在开头和结尾。
- 最后最好是for循环,因为尽量不要去动l和r(如果用while循环,l和r会变)。
代码如下:
class Solution {
public:
/**
* @param s: the string that represents a number
* @return: whether the string is a valid number
*/
bool isNumber(string &s) {
int n = s.size();
if (n == 0) return false;
int l = 0, r = n - 1;
while (l <= r && s[l] == ' ') l++; //or use isspace(s[l])
while (l <= r && s[r] == ' ') r--; //or use isspace(s[r])
if (l > r) return false;
if (s[l] == '+' || s[l] == '-') l++;
if (l > r) return false;
int pos_dot = -1, pos_e = -1;
for (int i = l; i <= r; ++i) {
//char c = tolower(s[i]);
char c = s[i];
if (isdigit(c)) continue;
if (c == '.') {
if (pos_dot < 0) pos_dot = i;
else return false;
} else if (c == 'e' || c == 'E') {
if (pos_e < 0) pos_e = i;
else return false;
} else {
return false;
}
}
if (pos_e == l || pos_e == r) return false;
if (pos_dot == l) return pos_dot < r && isdigit(s[pos_dot + 1]);
if (pos_dot == r) return pos_dot > l && isdigit(s[pos_dot - 1]);
return true;
}
};