zoukankan      html  css  js  c++  java
  • Valid Number

    Validate if a given string is numeric.

    Some examples:
    "0" => true
    " 0.1 " => true
    "abc" => false
    "1 a" => false
    "2e10" => true

    Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

    class Solution {
    public:
        bool isNumber(string s) {
            int len = s.length();
            int dotNum = 0;
            int eNum = 0;
    
            //去掉首位的空格
            int start = len;
            for(int i=0;i<len;i++){
                if(s[i] != ' '){
                    start = i;
                    break;
                }
            }
            for(int i=len-1;i>=0;i--){
                if(s[i] == ' '){
                    len--;
                }else{
                    break;
                }
            }
            if(start > len) return false;
    
            for(int i=start;i<len;i++){
                if(s[i] >= '0' && s[i] <= '9'){
                    continue;
                }else if(s[i] == '.'){
                    if(dotNum > 0 || eNum >0 ) return false;
                    dotNum++;
                    if(i == start && i == len-1) return false;
                    if(!(s[i-1] >= '0' && s[i-1] <= '9') && (i==len-1 || !(s[i+1] >= '0' && s[i+1] <= '9'))) return false;
                }else if(s[i] == 'e'){
                    if(eNum > 0) return false;
                    eNum++;
                    if(i==start) return false;
                    if(s[i-1] == '-' || s[i-1] == '+')  return false;
                    if( i == len - 1)  return false;
                }else if(s[i] == '-'){
                    if(i != start && s[i-1] != 'e') return false;
                    if(i == len-1) return false;
                }else if(s[i] == '+'){
                    if(i != start && s[i-1] != 'e') return false;
                    if(i==len-1) return false;
                }else{
                    return false;
                }
            }
            return true;
    
        }
    };
  • 相关阅读:
    2.完全背包问题
    1.01背包问题
    19.区间合并
    18.区间和
    16.数组元素的目标和
    15.最长连续不重复子序列
    14.差分矩阵
    1.注册七牛云账号
    1.1 linux查看系统基本参数常用命令
    图书管理增删改查&父子调用&前后端
  • 原文地址:https://www.cnblogs.com/wxquare/p/5869930.html
Copyright © 2011-2022 走看看