[LintCode] Valid Number 验证数字

简介:

Validate if a given string is numeric.

Example

"0" => true

" 0.1 " => true

"abc" => false

"1 a" => false

"2e10" => true

LeetCode上的原题,请参见我之前的博客Valid Number

class Solution {
public:
    /**
     * @param s the string that represents a number
     * @return whether the string is a valid number
     */
    bool isNumber(string& s) {
        bool num = false, numAfterE = true, dot = false, exp = false, sign = false;
        int n = s.size();
        for (int i = 0; i < n; ++i) {
            if (s[i] == ' ') {
                if (i < n - 1 && s[i + 1] != ' ' && (num || dot || exp || sign)) return false;
            } else if (s[i] == '+' || s[i] == '-') {
                if (i > 0 && s[i - 1] != 'e' && s[i - 1] != ' ') return false;
                sign = true;
            } else if (s[i] >= '0' && s[i] <= '9') {
                num = true;
                numAfterE = true;
            } else if (s[i] == '.') {
                if (dot || exp) return false;
                dot = true;
            } else if (s[i] == 'e') {
                if (exp || !num) return false;
                exp = true;
                numAfterE = false;
            } else return false;
        }
        return num && numAfterE;
    }
};

本文转自博客园Grandyang的博客,原文链接:验证数字[LintCode] Valid Number ,如需转载请自行联系原博主。

相关文章
|
算法
LeetCode 65. Valid Number
验证给定字符串是否可以解释为十进制数。
64 0
LeetCode 65. Valid Number
|
存储 算法
[leetcode/lintcode 题解] 阿里算法面试真题:丑数 II · Ugly Number II
[leetcode/lintcode 题解] 阿里算法面试真题:丑数 II · Ugly Number II
[leetcode/lintcode 题解] 阿里算法面试真题:丑数 II · Ugly Number II
|
Java 数据安全/隐私保护
[LintCode] Number of Islands(岛屿个数)
描述 给一个01矩阵,求不同的岛屿的个数。 0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。 样例 在矩阵: [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1] ] 中有 3 个岛。
1226 0
|
机器学习/深度学习