zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    【题解】B进制星球
    高斯消元
    7.16
    题解 P1572 【计算分数】
    7.30
    7.31
    项目中使用 MyBatis(一)
    从整体上了解Spring MVC
    Spring注解
    Spring IOC 和 DI
  • 原文地址:https://www.cnblogs.com/grandyang/p/5747730.html
Copyright © 2011-2022 走看看